[英]Using Counter in Python, how do I filter the most common words
我试图找到在导出到.txt文件的whatsapp聊天中使用的最常用单词。 此代码有效...
from collections import Counter
import re
words = re.findall(r'\w+', open('chat.txt').read().lower())
print(Counter(words).most_common(10))
...但是它包括所有日期以及我自己的名字和收件人的名字。 我可以添加什么使其忽略某些单词? (我敢肯定有一个非常简单的解决方案,但我对python还是很陌生。)谢谢!
编辑:
我现在所理解的问题并没有很好地解释。 我意识到我不太具体,因为我主要只是复制代码示例并尝试有效的方法,而不是分析代码本身。
我试图在.txt文件中找到最常见的词,该文件是一个已存档的whatsapp聊天,这是一个无聊的示例:
“ [06/12/2017,18:09:10] Name1姓氏1:现在就在管子上
[06/12/2017,18:09:29] Name1 Surname1:带我走了25分钟,所以我很想把它剪下来
[06/12/2017,18:36:16] Name2 Surname2:我只是在11号平台旁等候
[16/12/2017,00:06:34] Name2 Surname2:我的邮件未发送
[16/12/2017,00:10:55] Name1姓氏1:
[16/12/2017,00:11:14] Name1姓氏1:由于某种原因,这些只是通过“
在使用以上代码对这篇文章进行的第一次编辑中,结果如下:
[('2018', 8552), ('name1', 6753), ('surname1', 6625), ('02', 4520), ('03', 3810), ('i', 3322), ('you', 2275), ('name2', 2016), ('01', 1995), ('surname2', 1991)]
所以它包括日期和名称,我想排除。
但是此代码:
from collections import Counter
with open('_chat.txt') as fin:
counter = Counter(fin.read().strip().split())
print(counter.most_common(10))
不包括数字。 但是,它仍然包含一些不需要的单词(例如名称)和“无意义的”单词(例如“ the”和“ and”):
[('Name1', 6686), ('Surname1:', 6615), ('I', 2277), ('Name2', 2000), ('Surname2:', 1990), ('you', 1714), ('to', 1488), ('and', 1084), ('a', 885), ('the', 881)]
我可以添加些什么来删除这类单词?
我了解这类似于如何在不调用RuntimeError的情况下使用循环删除Counter对象中的条目? 但是当我尝试类似地格式化我的代码时,它并没有成功,并且对它的工作方式也有些困惑。 (很抱歉,当我说我对python很陌生时,我的意思是非常新。)
查看您的输入内容,建议您先清洁它,然后再将其放入Counter
。
如果您的文件带有如下所示的行:
[06/12/2017, 18:09:10] Name1 Surname1: just on the tube now
然后,您可以通过查找[第一个结束]
来清除日期,然后在其后进行分割,然后通过对:
做类似的操作来清除名称。 可以使用file.readlines()
读取文件中的行,然后对每个行进行处理,例如
with open('chat.txt') as f:
lines = f.readlines()
def clean_line(line):
"""
Find the first ], assume it's followed by a space and
slice off everything after that
Split the line on the first : and take the second part
of the resulting list
"""
return line[line.find(']')+2:].split(':', 1)[1]
words = []
for line in lines:
words += clean_line(line).lower().split()
counted_words = Counter(words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.