在Python中使用Counter,如何过滤最常见的单词

时间:2018-04-01 22:04:18

标签: python regex counter

我试图找到导出到.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]姓名1姓氏1:刚好在管子上

[06/12/2017,18:09:29]姓名1姓氏:我需要25分钟,所以我要把它剪得很好

[06/12/2017,18:36:16]姓名2姓氏2:我只是在11号平台等候

[16/12/2017,00:06:34]姓名2姓:我的留言没有发送

[16/12/2017,00:10:55]姓名1姓氏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))

不包含数字。然而,它仍然包括一些不需要的词,如名称和"无意义"像''和'和':

[('Name1', 6686), ('Surname1:', 6615), ('I', 2277), ('Name2', 2000), ('Surname2:', 1990), ('you', 1714), ('to', 1488), ('and', 1084), ('a', 885), ('the', 881)]

我可以添加什么来删除这些词?

我理解这类似于How do I remove entries within a Counter object with a loop without invoking a RuntimeError? 但是当我尝试使用类似的方式格式化我的代码时,它还没有成功,并且对它的工作原理感到有点困惑。 (对不起,因为我说我对python很新,我的意思是非常新的。)

1 个答案:

答案 0 :(得分:0)

查看您的输入我建议您在将其输入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)
相关问题