[英]str object not callable
我正在嘗試將可以在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
我認為您的診斷是錯誤的。 該錯誤實際上發生在以下行:
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()
如何在循環體內移動。
您正在傳遞一個字符串作為map的第一個參數,它期望一個callable作為它的第一個參數:
lines = map(str.strip(' '),map(str.lower,f1.readlines()))
我認為您需要以下條件:
lines = map( lambda x: x.strip(' '), map(str.lower, f1.readlines()))
它將在另一個map
調用的結果中對每個字符串調用strip
。
另外,不要將str
用作變量名,因為這是內置函數的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.