簡體   English   中英

Python:我有一個單詞列表,想檢查這些單詞在文件的每一行中出現的次數

[英]Python: I have a list of words, and want to check the number of occurrences of those words in each line in a file

所以我想計算文本文件中每行某些單詞的出現次數。 每個特定單詞出現多少次並不重要,重要的是每行出現了多少次。 我有一個包含單詞列表的文件,由換行符分隔。 它看起來像這樣:

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

有任何想法嗎?

這個怎么樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM