我正试图写一个程序,我计数最常用的字从一个文件,但这些话不应该在另一个文件中。所以基本上我是从测试.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)
下面是我的方法-使用集合
这应该是稍微快一点,以及你做了一个计数器上只有'所有的\'的话
我只是简单地修改了你原来代码的下面一行
f = open('test2.txt', 'rb')
至
f = open('test2.txt', 'r')
而且成功了。只需将文本读取为字符串而不是二进制文件。否则它们在正则表达式中就不匹配了。在python3.4eclipsepydevwin7x64上测试。你知道吗
离题:
使用带有语句的打开文件更像python。在这种情况下,写
with open('test2.txt', 'r') as f:
并相应地缩进文件处理语句。这样可以避免忘记关闭文件流。你知道吗
相关问题 更多 >
编程相关推荐