List objects are un-hashable
Michael Hoffman
cam.ac.uk at mh391.invalid
Fri Apr 27 04:39:37 EDT 2007
Andy wrote:
> Hi, I'm trying to search and print any no# of Python keywords present
> in a text file (say - foo.txt), and getting the above error. Sad for
> not being able to decipher such a simple problem (I can come up with
> other ways - but want to fix this one FFS).
It helps a lot of if you post the traceback with your problem. The line
it occurred on is crucial for debugging.
But I will use my psychic debugger which tells me that the error is here:
> if keyword.iskeyword(tempwords):
tempwords is a list. You need to iterate over the contents of the list
and run keyword.iskeyword() for each one. Here's an example for Python
2.5. I've cleaned up some extra lines of code that didn't have any
eventual effects in your current implementation
from __future__ import with_statement
import keyword
INFILENAME = "foo.txt"
with open(INFILENAME) as infile:
for line in infile:
words = line.split()
for word in words:
if keyword.iskeyword(word):
print word
This will print multiple lines per input line. If you wanted one line
per input line then try:
with open(INFILENAME) as infile:
for line in infile:
words = line.split()
print " ".join(word for word in words
if keyword.iskeyword(word))
--
Michael Hoffman
More information about the Python-list
mailing list