0

2 レベルの深さの辞書があります。つまり、最初のディクショナリの各キーは 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 回表示されます: 単語のリスト

4

2 に答える 2

0

カウンターはあなたが望むものではありません。表示された出力から、単語が出現する合計数とページ数の両方を追跡したいようです。

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、 '上位 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)
于 2013-04-10T19:00:06.740 に答える