用python打印每行有n个元素的词典

用python打印每行有n个元素的词典,python,sorting,dictionary,printing,Python,Sorting,Dictionary,Printing,给定一个包含200000行单词的.txt,我需要计算每个字母作为单词的第一个字母出现的次数。我有一个带有“a”-“z”键的字典,每个键的值都有计数。我需要在表格上打印出来 a:10,978 b:7,890 c:12,201 d:9,562 e:6,008 f:7,095 g:5,660 (...) 这本词典目前是这样印刷的 [('a', 10898), ('b', 9950), ('c', 17045), ('d', 10675), ('e', 7421), ('f', 7138), ('g'

给定一个包含200000行单词的.txt,我需要计算每个字母作为单词的第一个字母出现的次数。我有一个带有“a”-“z”键的字典,每个键的值都有计数。我需要在表格上打印出来

a:10,978 b:7,890 c:12,201 d:9,562 e:6,008
f:7,095 g:5,660 (...)
这本词典目前是这样印刷的

[('a', 10898), ('b', 9950), ('c', 17045), ('d', 10675), ('e', 7421), ('f', 7138), ('g', 5998), ('h', 6619), ('i', 7128), ('j', 1505), ('k'...
如何删除括号和圆括号并每行仅打印5个计数?另外,在我按键对字典排序后,它开始以key,value而不是key:value打印

def main():
    file_name = open('dictionary.txt', 'r').readlines()
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    letter = {}
    for i in alphabet:
        letter[i]=0
    for n in letter:
        for p in file_name:
            if p.startswith(n):
                letter[n] = letter[n]+1
    letter = sorted(letter.items())
    print(letter)
main()

您可以使用以下选项:

for grp in range(0, len(letter), 5):
    print(' '.join(elm[0] + ':' + '{:,}'.format(elm[1]) for elm in letter[grp:grp+5]))




a:10,898 b:9,950 c:17,045 d:10,675 e:7,421
f:7,138 g:5,998 h:6,619 i:7,128 j:1,505
它在列表中循环,按5个元素分组,然后以所需格式打印

在[15]中:

letter = [('a', 10898), ('b', 9950), ('c', 17045), ('d', 10675), ('e', 7421), ('f', 7138), ('g', 5998), ('h', 6619), ('i', 7128), ('j', 1505)]
将打印(字母)替换为以下内容:

for grp in range(0, len(letter), 5):
    print(' '.join(elm[0] + ':' + '{:,}'.format(elm[1]) for elm in letter[grp:grp+5]))




a:10,898 b:9,950 c:17,045 d:10,675 e:7,421
f:7,138 g:5,998 h:6,619 i:7,128 j:1,505

A collections.Counter dict将获得每行上所有第一个字母的计数,然后拆分为块并合并:

from collections import Counter

with open('dictionary.txt') as f: # automatically closes your file
    # iterate once over the file object as opposed to storing 200k lines
    # and 26 iterations over the lines
    c = Counter(line[0] for line in f)
    srt = sorted(c.items())
    # create five element chunks from  the sorted items
    chunks = (srt[i:i+5] for i in range(0, len(srt), 5))
    for chk in chunks:
        # format and join
        print(" ".join("{}:{:,}".format(c[0],c[1]) for c in chk))
如果您可能有字母a-z以外的内容,请在循环中使用isalpha:

c = Counter(line[0] for line in f if line[0].isalpha())

Python2.7中添加了一个字母。

您正在读取每个字母的整个文件。您应该通过文件传递一次,然后增加正确的计数。我可以通过将“for n in letter”循环放入for“p in file_name”循环中来实现这一点“,对吗?计数器将更有效地执行您想要的操作,您的逻辑看起来也有点可疑,但这是有效的。”。你能解释一下我的逻辑看起来有点可疑吗?我正在学习一门计算机科学的入门课程,我对所有这些都是全新的。对于文件名中的p,你要在列表上重复26次,而不是只做一次。如果你打算换一种方式,你会使用字母p[0]中的
,只需在单词列表上做一个循环,然后忘记在dict上的循环。你的代码效率很低,一次将所有200000行存储在内存中,并进行25次不必要的迭代。这是对我的问题最直接的回答, thanks@zachapp注意:这将只打印5组。如果要打印仅包含1个字母的行(例如“z”计数),则必须对其进行修改