Question

I am trying to convert a program that worked fine with Python 2.7.2 to Python 3.1.4.

I am getting

TypeError: Str object not callable for the following code on the line "for line in lines:"

code:

in_file = "INPUT.txt"
out_file = "OUTPUT.txt"

##The following code removes creates frequencies of words

# create list of lower case words, \s+ --> match any whitespace(s)
d1=defaultdict(int)
f1 = open(in_file,'r')
lines = map(str.strip(' '),map(str.lower,f1.readlines()))
f1.close()        
for line in lines:
    s = re.sub(r'[0-9#$?*><@\(\)&;:,.!-+%=\[\]\-\/\^]', " ", line)
    s = s.replace('\t',' ')
    word_list = re.split('\s+',s)
    unique_word_list = [word for word in word_list]  
    for word in unique_word_list:
        if re.search(r"\b"+word+r"\b",s):
            if len(word)>1:
                d1[word]+=1 
Was it helpful?

Solution

You're passing a string as the first argument to map, which expects a callable as its first argument:

lines = map(str.strip(' '),map(str.lower,f1.readlines()))

I think you want the following:

lines = map( lambda x: x.strip(' '), map(str.lower, f1.readlines()))

which will call strip on each string in the result of the other call to map.

Also, don't use str as a variable name, as that is the name of a built-in function.

OTHER TIPS

I think your diagnostic is wrong. The error actually happens on the following line:

lines = map(str.strip(' '),map(str.lower,f1.readlines()))

My recommendation would be to change the code as follows:

in_file = "INPUT.txt"
out_file = "OUTPUT.txt"

##The following code removes creates frequencies of words

# create list of lower case words, \s+ --> match any whitespace(s)
d1=defaultdict(int)
with open(in_file,'r') as f1:
    for line in f1:
        line = line.strip().lower()
        ...

Note the use of the with statement, the iteration over the file, and how strip() and lower() got moved inside the body of the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top