2012-02-20 84 views
0

我有一段文字,我在python中创建了一本字典。它包含文字作为关键字,文字中出现的文字作为值的次数。该字典按值字段的值递减排序。这里是我的清单的片段:Python中的字典操作

[('the\n', 1644), ('and\n', 872), ('to\n', 729), ('a\n', 632), ('she\n', 541), 
('it\n', 530), ('of\n', 514), ('said\n', 462), ('i\n', 410), ('alice\n', 386), 
('in\n', 369), ('you\n', 365), ('was\n', 357), ('that\n', 280), ('as\n', 263), 
('her\n', 248), ('at\n', 212), ('on\n', 193), ('all\n', 182), ('with\n', 181), 
('had\n', 178), ('but\n', 170), ('for\n', 153), ('so\n', 151), ('be\n', 148), 
('not\n', 145), ('very\n', 144), ('what\n', 136), ('this\n', 134), 
('they\n', 130), ('little\n', 128), ('he\n', 120), ('out\n', 117), 
('is\n', 108), ... ] 

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

此外,我必须添加所有单词的排名。例如,在我的字典中,“the”将被排名为1,“和”2等等。我如何在单词列表中添加一个排名?

回答

2

只是筛选使用列表理解:

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

由于原来的列表进行排序,所以这将是一个。然后,你可以切它让高层25:f_words[:25]

+0

如果我想从1-25开始对这些文档进行排名,我如何在关键字:值对列表中包含排名? – Nerd 2012-02-20 22:06:06

+0

您可以使用'enumerate(some_list,1)'获取(索引,元素)对。 '1'表示起点,否则从0开始计数。 – tzaman 2012-02-20 22:48:02

3

一种选择是使用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个单词后停止。