0

我有一本两层深的字典。也就是说,第一个字典中的每个键都是一个 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

4

看来您应该Counter为此使用 a :

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)

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

c = Counter((k,v) for k,v in c.items() if k in s)
print c.most_common()
于 2013-04-10T18:27:51.463 回答
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单词。您可以使用 heapsort 来做到这一点(它的方便功能是不需要您按页数然后出现次数对整个单词列表进行排序 - 如果您总共有很多单词,这可能很重要,但是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)
于 2013-04-10T19:00:06.740 回答