繁体   English   中英

如何在python词典中找到最常见的条目

[英]how to find most common entry in dictionary of dictionaries in python

我有一本深两级的字典。 也就是说,第一个字典中的每个键都是一个URL,值是另一个字典,每个键是单词,每个值是单词出现在该URL上的次数。 看起来像这样:

dic = {
    'http://www.cs.rpi.edu/news/seminars.html': {
        'hyper': 1,
        'summer': 2,
        'expert': 1,
        'koushk': 1,
        'semantic': 1,
        'feedback': 1,
        'sandia': 1,
        'lewis': 1,
        'global': 1,
        'yener': 1,
        'laura': 1,
        'troy': 1,
        'session': 1,
        'greenhouse': 1,
        'human': 1

...and so on...

字典本身很长,里面有25个url,每个url都有另一个字典作为其值,其中每个单词都在url中找到,并且找到了它的次数。

我想找到出现在词典中最不同的URL中的一个或多个单词。 因此输出应如下所示:

以下单词在y页上出现x次:单词列表

看来您应该为此使用Counter

from collections import Counter
print sum((Counter(x) for x in dic.values()),Counter()).most_common()

或多行版本:

c = Counter()
for d in dic.values():
    c += Counter(d)

print c.most_common()

要获得所有子句中常见的词:

subdicts = iter(dic.values())
s = set(next(subdicts)).intersection(*subdicts)

现在,您可以使用该设置来过滤结果计数器,删除未在每个下级中出现的单词:

c = Counter((k,v) for k,v in c.items() if k in s)
print c.most_common()

柜台并不是您想要的。 从显示的输出中,您似乎想同时跟踪出现的总数和单词在其上出现的页面数。

data = {
    'page1': {
        'word1': 5,
        'word2': 10,
        'word3': 2,
    },
    'page2': {
        'word2': 2,
        'word3': 1,
    }
}

from collections import defaultdict
class Entry(object):
    def __init__(self):
        self.pages = 0
        self.occurrences = 0
    def __iadd__(self, occurrences):
        self.pages += 1
        self.occurrences += occurrences
        return self
    def __str__(self):
        return '{} occurrences on {} pages'.format(self.occurrences, self.pages)
    def __repr__(self):
        return '<Entry {} occurrences, {} pages>'.format(self.occurrences, self.pages)

counts = defaultdict(Entry)

for page_words in data.itervalues():
    for word, count in page_words.iteritems():
        counts[word] += count

for word, entry in counts.iteritems():
    print word, ':', entry

这将产生以下输出:

word1 : 5 occurrences on 1 pages
word3 : 3 occurrences on 2 pages
word2 : 12 occurrences on 2 pages

这将捕获您想要的信息,下一步将是查找最常见的n单词。 您可以使用堆排序来做到这一点(它具有方便的功能,它不需要按照单词的出现次数对整个单词列表进行排序-如果您总共有很多单词,那么这很重要,但是其中n个'top n'相对较小)。

from heapq import nlargest
def by_pages_then_occurrences(item):
    entry = item[1]
    return entry.pages, entry.occurrences
print nlargest(2, counts.iteritems(), key=by_pages_then_occurrences)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM