社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

计算python中两个单词的所有组合的频率[duplicate]

Duy Nguyen • 7 年前 • 1807 次点击  

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

"I have 2 laptops, I have 2 chargers"

结果应该是:

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

我试过regex,但问题是它不计算两次字符串

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

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

它几乎可以工作,但不包括“存储设备”, cooling system 因为它已经 energy storage 和 industrial cooling

感谢你的建议

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43979
文章 [ 1 ]  |  最新文章 7 年前
Sunitha
Reply   •   1 楼
Sunitha    7 年前

你可以使用 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
}