0

我正在尝试将适用于 Python 2.7.2 的程序转换为 Python 3.1.4。

我正进入(状态

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

代码:

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 
4

2 回答 2

6

我认为你的诊断是错误的。该错误实际上发生在以下行:

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

我的建议是更改代码如下:

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()
        ...

请注意with语句的使用、对文件的迭代以及如何strip()lower()循环体内移动。

于 2012-02-06T16:50:27.160 回答
6

您将一个字符串作为第一个参数传递给 map,它需要一个可调用对象作为它的第一个参数:

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

我认为您想要以下内容:

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

它将strip在另一个调用的结果中调用每个字符串map

另外,不要str用作变量名,因为这是内置函数的名称。

于 2012-02-06T16:52:30.077 回答