str对象不可调用

0 投票
2 回答
3304 浏览
提问于 2025-04-17 12:26

我正在尝试把一个在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 

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() 被放到了循环的内部。

6

你把一个字符串当作第一个参数传给了map,但map希望第一个参数是一个可以调用的东西:

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

我觉得你想要的是这个:

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

这样会对另一个map调用的结果中的每个字符串都执行strip操作。

另外,不要把str当作变量名,因为那是一个内置函数的名字。

撰写回答