在使用Python的另一个文件中找不到的一个文件中最常见的单词

2024-06-16 10:07:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个程序,我计数最常用的字从一个文件,但这些话不应该在另一个文件中。所以基本上我是从测试.txt并从该文件中计算最常用的单词,但该单词不应在test2.txt文件中找到。你知道吗

下面是示例数据文件,测试.txt和test2.txt

你知道吗测试.txt地址:

The Project is for testing. doing some testing to find what's going on. the the the.

test2.txt文件:

a
about
above
across
after
afterwards
again
against
the

下面是我的脚本,它解析文件测试.txt和test2.txt。它可以从中找到最常用的单词测试.txt,不包括test2.txt中的单词。你知道吗

我以为我做的一切都是对的,但当我执行脚本时,它给出了“the”作为最常用的词。但实际上,结果应该是“testing”,因为test2.txt中有“the”,而test2.txt中没有“testing”。你知道吗

from collections import Counter
import re

dgWords = re.findall(r'\w+', open('test.txt').read().lower())

f = open('test2.txt', 'rb')
sWords = [line.strip() for line in f]

print(len(dgWords));

for sWord in sWords:
    print (sWord)
    print (dgWords) 
    while sWord in dgWords: dgWords.remove(sWord)   

print(len(dgWords));
mostFrequentWord = Counter(dgWords).most_common(1)
print (mostFrequentWord)

Tags: 文件theinimportretxt脚本for
3条回答

下面是我的方法-使用集合

all_words = re.findall(r'\w+', open('test.txt').read().lower())

f = open('test2.txt', 'rb')
stop_words = [line.strip() for line in f]

set_all = set(all_words)
set_stop = set(stop_words)

all_only = set_all - set_stop

print Counter(filter(lambda w:w in all_only, all_words)).most_common(1)

这应该是稍微快一点,以及你做了一个计数器上只有'所有的\'的话

import re
from collections import Counter

with open('test.txt') as testfile, open('test2.txt') as stopfile:
    stopwords = set(line.strip() for line in stopfile)
    words = Counter(re.findall(r'\w+', open('test.txt').read().lower()))
    for word in stopwords:
        if word in words:
            words.pop(word)
    print("the most frequent word is", words.most_common(1))

我只是简单地修改了你原来代码的下面一行

f = open('test2.txt', 'rb')

f = open('test2.txt', 'r')

而且成功了。只需将文本读取为字符串而不是二进制文件。否则它们在正则表达式中就不匹配了。在python3.4eclipsepydevwin7x64上测试。你知道吗

离题:

使用带有语句的打开文件更像python。在这种情况下,写

with open('test2.txt', 'r') as f:

并相应地缩进文件处理语句。这样可以避免忘记关闭文件流。你知道吗

相关问题 更多 >