str 对象不可调用
我正在尝试将一个在 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
I am trying to convert a program that worked fine with Python 2.7.2 to Python 3.1.4.
I am getting
TypeError: Str object not callable for the following code on the line "for line in lines:"
code:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将一个字符串作为第一个参数传递给 map,它需要一个可调用对象作为其第一个参数:
我认为您需要以下内容:
它将在另一个调用的结果中的每个字符串上调用
strip
到地图
。另外,不要使用
str
作为变量名,因为这是内置函数的名称。You're passing a string as the first argument to map, which expects a callable as its first argument:
I think you want the following:
which will call
strip
on each string in the result of the other call tomap
.Also, don't use
str
as a variable name, as that is the name of a built-in function.我认为你的诊断是错误的。该错误实际上发生在以下行:
我的建议是更改代码,如下所示:
注意
with
语句的使用、文件上的迭代以及如何strip()< /code> 和
lower()
被移动到循环体内。I think your diagnostic is wrong. The error actually happens on the following line:
My recommendation would be to change the code as follows:
Note the use of the
with
statement, the iteration over the file, and howstrip()
andlower()
got moved inside the body of the loop.