Python:我有一个单词列表,希望检查fi中每行出现这些单词的次数

2024-10-04 01:34:52 发布

您现在位置: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

有什么想法吗?你知道吗


Tags: incountlinegreen单词veryflag文本文件
1条回答
网友
1楼 · 发布于 2024-10-04 01:34:52

这个怎么样:

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

相关问题 更多 >