簡體   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