【问题标题】:Find most common multi words in an input file in Python在 Python 中的输入文件中查找最常见的多词
【发布时间】:2021-05-19 02:31:38
【问题描述】:

假设我有一个文本文件,我可以使用 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)

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

【问题讨论】:

  • [word for word in words] 什么都不做; words 已经是一个列表

标签: python python-3.x nltk


【解决方案1】:

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

nltk 库非常适合执行大量与语言相关的任务,您可以使用 collections 中的 Counter 处理所有与计数相关的任务活动!

import nltk
from nltk import bigrams
from collections import Counter

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

【讨论】:

  • 谢谢!但对于“for”,我不断收到第 7 行的“SyntaxError: invalid syntax”。
  • 我简化了答案,让我知道结果如何!
  • 这很好用!如果允许,我会接受这个答案。
【解决方案2】:

你所说的多词(没有这样的东西)实际上被称为二元词。你可以从单词列表中获取一个二元组列表,方法是使用位移对其自身进行压缩:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多