繁体   English   中英

在 Python 的输入文件中查找最常见的多词

[英]Find most common multi words in an input file in Python

假设我有一个文本文件,我可以使用 Counter 轻松找到最常用的单词。 但是,我也想找到诸如“纳税年度、飞钓、美国国会大厦等”之类的多个词。 一起出现最多的词。

import re
from collections import Counter

with open('full.txt') as f:
    passage = f.read()

words = re.findall(r'\w+', passage)

cap_words = [word for word in words]

word_counts = Counter(cap_words)

for k, v in word_counts.most_common():
    print(k, v)

我目前有这个,但是,这只找到一个词。 如何找到多个单词?

您正在寻找的是一种计算二元组(包含两个单词的字符串)的方法。

nltk库非常适合执行许多与语言相关的任务,您可以使用collectionsCounter进行所有与计数相关的活动!

import nltk
from nltk import bigrams
from collections import Counter

tokens = nltk.word_tokenize(passage)
print(Counter(bigrams(tokens))

你所说的多词(没有这样的东西)实际上被称为二元组。 您可以通过使用位移将其与自身压缩来从单词列表中获取二元组列表:

bigrams = [f"{x} {y}" for x,y, in zip(words, words[1:])]

PS NLTK 确实是获得二元组的更好工具。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM