确实需要一些帮助来解决此问题,或者如果有人可以用正确的方式指出我,谢谢!
查看文本中找到的7个最常见的单词,但对作为常见单词的单词进行排序。您可以在common-words.txt中找到常见单词的列表。
common-words.txt =许多不同的单词。
首先,我在文本中找到了7个最常用的词,这就是我的代码的样子。
print("The 7 most frequently used words is:")
print("\n")
import re
from collections import Counter
with open("alice-ch1.txt") as f:
passage = f.read()
words = re.findall(r'\w+', passage)
cap_words = [word.upper() for word in words]
word_counts = Counter(cap_words).most_common(7)
print(word_counts)
这有效,我得到了输出:
[('THE', 93), ('SHE', 80), ('TO', 75), ('IT', 67), ('AND', 65), ('WAS', 53), ('A', 52)]
现在,我想比较这两个文本文件,如果我的TEXTFILE.TXT中的任何单词在COMMON-WORDS.TXT中,我希望将其从答案中删除。
我试图用以下代码运行它:
dic_no_cw = dict(word_counts)
with open("common-words.txt", 'r') as cw:
commonwords = list(cw.read().split())
for key, value in list(dic_no_cw.items()):
for line in commonwords:
if key == line:
del dic_no_cw[key]
dict_copy = dict(dic_no_cw)
dic_no_cw7 = Counter(dic_no_cw).most_common(7)
sorted(dic_no_cw7)
print(dic_no_cw7)
和我得到相同的输出:
[('THE', 93), ('SHE', 80), ('TO', 75), ('IT', 67), ('AND', 65), ('WAS', 53), ('A', 52)]
可以真的使用som帮助来解决此问题或一些帮助,以便我自己解决。
谢谢,
您是否可以尝试替换以下代码行:
for line in commonwords:
if key == line:
del dic_no_cw[key]
和
for line in commonwords:
if key.strip() == line.upper().strip():
del dic_no_cw[key]
break
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句