我正在尝试使用 python 按字母顺序对双字母组元组列表进行排序。我的输出现在看起来像这样:
('hello', 'how')
('how', 'are')
('are', 'you')
('you', '?')
('Are', 'you')
('you', 'okay')
('okay', '?')
我希望输出看起来像这样,按字母顺序排列并且每个二元组只出现一次,最好有一个频率计数:
('are', 'you'), 2
('hello', 'how'), 1
('how', 'are'), 1
('okay', '?'), 1
('you', 'okay'), 1
('you', '?'), 1
我的代码是这样的:
def bigram(x):
with open (x, 'r', encoding='utf-8') as f:
mylist = f.read()
n = 2
grams = ngrams(nltk.word_tokenize(mylist), n)
for bigrams in grams:
return bigrams
非常感谢您的帮助,谢谢!
最佳答案
你需要做几个步骤(在阅读grams
之后):
首先,将所有内容小写以便于查找 double :
grams = [ (a.lower(), b.lower()) for (a, b) in grams ]
其次,将 grams
分组并计数:
import collections
counted = collections.Counter(grams)
第三,对计数的东西进行排序:
for gram, count in sorted(counted.items()):
print gram, count
关于python - 按字母顺序对元组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203713/