2012-02-06 56 views
0

我想将一个可以正常使用Python 2.7.2的程序转换为Python 3.1.4。str对象无法调用

我越来越

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 

回答

6

你传递一个字符串作为第一个参数映射,这需要一个可调用的第一个参数:

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

我想你想以下几点:

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

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

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

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()被移到了循环体内。

相关问题