2016-03-23 2 views
1

したがって、テキストファイル内で特定の単語の出現を1行に数えたいと思う。特定の単語が何回出現したかは問題ではなく、1行に何回出現したかだけです。私は改行文字で区切られた単語のリストを含むファイルを持っています。Python:私は単語のリストを持っていて、ファイル内の各行の単語の出現数を確認したい。

amazingly 
astoundingly 
awful 
bloody 
exceptionally 
frightfully 
..... 
very 

次に、テキスト行を含む別のテキストファイルがあります。私は私の出力は次のようになりたい

frightfully frightfully amazingly Male. Don't forget male 
green flag stops? bloody bloody bloody bloody 
I'm biased. 
LOOKS like he was headed very 
green flag stops? 
amazingly exceptionally exceptionally 
astoundingly 
hello world 

3 
4 
0 
1 
0 
3 
1 

は、ここに私のコードです:

def checkLine(line): 
    count = 0 
    with open("intensifiers.txt") as f: 
     for word in f: 
      if word[:-1] in line: 
       count += 1 
    print count 


for line in open("intense.txt", "r"): 
    checkLine(line)     

ここに私の実際の出力です:

4 
1 
0 
1 
0 
2 
1 
0 

例えば貸し付け何か案は?

答えて

1

これはどう:

def checkLine(line): 
    with open("intensifiers.txt") as fh: 
     line_words = line.rstrip().split(' ') 
     check_words = [word.rstrip() for word in fh] 
     print sum(line_words.count(w) for w in check_words) 


for line in open("intense.txt", "r"): 
    checkLine(line)  

出力:

3 
4 
0 
1 
0 
3 
1 
0 
関連する問題