python - 按字母顺序对元组排序

标签 python python-2.7 python-3.x

我正在尝试使用 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/

相关文章:

python - 提高 Pandas DataFrames 的行追加性能

Python Cassandra - 保存文件给出 "Invalid STRING constant"

python - Pandas 列表中的词频

python-3.x - Plot_confusioin_matrix 图不显示整数值,而是显示一些指数值

python-3.x - 如何使用Azure通信电子邮件python sdk发送异步电子邮件

python - 本地python简单http服务器在Windows中发送错误的mime类型,但在Linux中不发送错误的mime类型 for.svg

python - AirFlow DAG 在 DST 后运行两次

python - python json正文请求中的德语元音变音

python - Plotly 不显示轴标签或标题

python-2.7 - 什么时候使用 zip 而不是 izip 更好?