Python中的字典操作



我有一段文本,并用python创建了一个字典。它以单词为键,以单词在文本中出现的次数为值。此字典按值字段的递减值进行排序。以下是我的列表片段:

[('then', 1644), ('andn', 872), ('ton', 729), ('an', 632), ('shen', 541), 
('itn', 530), ('ofn', 514), ('saidn', 462), ('in', 410), ('alicen', 386),
('inn', 369), ('youn', 365), ('wasn', 357), ('thatn', 280), ('asn', 263), 
('hern', 248), ('atn', 212), ('onn', 193), ('alln', 182), ('withn', 181),
('hadn', 178), ('butn', 170), ('forn', 153), ('son', 151), ('ben', 148), 
('notn', 145), ('veryn', 144), ('whatn', 136), ('thisn', 134),
('theyn', 130), ('littlen', 128), ('hen', 120), ('outn', 117),
('isn', 108), ... ]

我想打印25个最常用的单词。这很简单,我已经做到了。下一部分是打印以字母"f"开头的25个最常见的单词。如何找到它并将其添加到25个最常见单词的列表中?

此外,我还要加上所有单词的排名。例如,在我的字典中,"the"将被排在第1位,"and"将被列在第2位,依此类推。我如何在单词列表中添加排名?

一个选项是使用itertools.ifilter()itertools.islice():

f_words = islice(ifilter(lambda x: x[0].startswith("f"), words), 25)
for word, count in f_words:
    print word.rstrip()

代替ifilter(),您还可以使用生成器表达式:

f_words = islice((w for w, c in words if w.startswith("f")), 25)
for word in f_words:
    print word.rstrip()

这两种方法的优点都是不需要先过滤整个列表——循环将在25个单词后停止。

只需使用列表理解进行过滤:

f_words = [(word, freq) for (word, freq) in the_list if word.startswith('f')]

由于原始列表是排序的,所以这个列表也是排序的。然后,您可以将其切片以获得前25名:f_words[:25]

最新更新