str对象不可调用

Zen*_*ega 0 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:"
Run Code Online (Sandbox Code Playgroud)

码:

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 
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 6

我认为您的诊断错误.错误实际发生在以下行:

lines = map(str.strip(' '),map(str.lower,f1.readlines()))
Run Code Online (Sandbox Code Playgroud)

我的建议是更改代码如下:

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()
        ...
Run Code Online (Sandbox Code Playgroud)

注意,使用的with语句中,遍历所有文件,以及如何strip()lower()得到移动的循环体内部.


che*_*ner 6

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

lines = map(str.strip(' '),map(str.lower,f1.readlines()))
Run Code Online (Sandbox Code Playgroud)

我想你想要以下内容:

lines = map( lambda x: x.strip(' '), map(str.lower, f1.readlines()))
Run Code Online (Sandbox Code Playgroud)

这将调用strip另一个调用的结果中的每个字符串map.

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