str对象不可调用

时间:2012-02-06 16:46:31

标签: python string typeerror map-function

我正在尝试将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 个答案:

答案 0 :(得分: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()如何在循环体内移动。

答案 1 :(得分:6)

你传递一个字符串作为map的第一个参数,它希望一个callable作为它的第一个参数:

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

我想你想要以下内容:

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

会在另一次调用strip的结果中为每个字符串调用map

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