【问题标题】:Calculate the frequency of all the combination of 2 words in Python [duplicate]计算Python中2个单词的所有组合的频率[重复]
【发布时间】:2019-11-29 17:08:59
【问题描述】:

我有一段文字。我想计算 2 个单词的所有可能组合(2 个单词必须彼此相邻) 例如:

"I have 2 laptops, I have 2 chargers"

结果应该是:

"I have": 2
"have 2": 2
"2 laptops": 1
"Laptops, I": (Dont count)
"2 chargers": 1

我尝试了正则表达式,但问题是它不会两次计算一个字符串

我用过:\b[a-z]{1,20}\b \b[a-z]{1,20}\b

文字:cold chain, energy storage device, industrial cooling system

它几乎可以工作,但它不包括诸如“存储设备”、cooling system 之类的词,因为它已经使用了energy storageindustrial cooling

感谢您的建议

【问题讨论】:

标签: python regex pattern-matching frequency word-count


【解决方案1】:

您可以使用zip 获取每两个单词的组,然后使用Counter 获取频率

>>> from collections import Counter
>>> text = "I have 2 laptops, I have 2 chargers"
>>> words = text.split()

>>> d = {' '.join(words):n for words,n in Counter(zip(words, words[1:])).items() if not  words[0][-1]==(',')}
>>> print (d)
{'I have': 2, 'have 2': 2, '2 laptops,': 1, '2 chargers': 1}

>>> import json
>>> print (json.dumps(d, indent=4))
{
    "I have": 2,
    "have 2": 2,
    "2 I": 1,
    "2 chargers": 1
}

【讨论】:

  • 您好,感谢您的回复。我试过你的方法。它有效,但我们如何排除那些包含逗号“,”的“笔记本电脑,我”?我必须经过数千行才能对 2 个单词组合进行统计,排除中间有逗号的单词很重要
  • 顺便说一句,我工作中的一个示例文本是这样的:“旧链,储能设备,工业冷却系统,工业物联网,智能存储,托管服务平台提供商,电源管理,制冷剂,热储能” 。因此,如果我使用您的方法,则会出现很多在 bettwen 或 word-end 中带有逗号的 2 词短语。我想排除那些结果
  • 我已更新答案以排除带逗号的单词
猜你喜欢
  • 2015-01-07
  • 1970-01-01
  • 2019-01-27
  • 2023-03-22
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
相关资源
最近更新 更多