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