2012-02-06 57 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()被移到了循環體內。

相關問題