0

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 
4

2 に答える 2

6

map の最初の引数として文字列を渡しています。これは、最初の引数として callable を想定しています。

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

私はあなたが次のことを望んでいると思います:

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

stripへの他の呼び出しの結果の各文字列を呼び出しますmap

strまた、組み込み関数の名前であるため、変数名として使用しないでください。

于 2012-02-06T16:52:30.077 に答える
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()

于 2012-02-06T16:50:27.160 に答える