【问题标题】:How to find the most frequent words in alphabetical order?如何按字母顺序查找最常用的单词?
【发布时间】:2013-11-19 21:31:06
【问题描述】:

我试图在这个不同的程序中按字母顺序查找文本文件中最常用的单词。

例如,单词:“that”是文本文件中出现频率最高的单词。所以,应该先打印出来:“那个#”

它需要采用这种格式作为程序和下面的答案:

d = dict()

def counter_one():
    d = dict()
    word_file = open('gg.txt')
    for line in word_file:
        word = line.strip().lower()
        d = counter_two(word, d)
    return d

def counter_two(word, d):
    d = dict()
    word_file = open('gg.txt')
    for line in word_file:
        if word not in d:
            d[word] = 1
        else:
            d[word] + 1
    return d

def diction(d):
    for key, val in d.iteritems():
        print key, val

counter_one()
diction(d)

它应该在 shell 中运行类似这样的东西:

>>>
Words in text: ###
Frequent Words: ###
that 11
the 11
we 10
which 10
>>>

【问题讨论】:

    标签: python word frequency numerical alphabetical


    【解决方案1】:

    获取频率计数的一种简单方法是使用内置集合模块中的Counter class。它允许您传入一个单词列表,它会自动计算所有单词并将每个单词映射到它的频率。

    from collections import Counter
    frequencies = Counter()
    with open('gg.txt') as f:
      for line in f:
        frequencies.update(line.lower().split())
    

    我使用lower() 函数来避免分别计算“the”和“The”。

    然后你可以用frequencies.most_common()frequencies.most_common(n)按频率顺序输出它们,如果你只想要顶部的n

    如果您想按频率对结果列表进行排序,然后按字母顺序为具有相同频率的元素排序,您可以使用带有key 参数lambda (x,y): (y,x)sorted 内置函数。因此,您执行此操作的最终代码是:

    from collections import Counter
    frequencies = Counter()
    with open('gg.txt') as f:
      for line in f:
        frequencies.update(line.lower().split())
    most_frequent = sorted(frequencies.most_common(4), key=lambda (x,y): (y,x))
    for (word, count) in most_frequent:
      print word, count
    

    那么输出会是

    that 11
    the 11
    we 10
    which 10
    

    【讨论】:

    • 如果您使用的是 Python 3,则应将 lambda 更改为 key=lambda x: (x[1], x[0])(参见 this
    【解决方案2】:

    您可以使用集合的Counter 更简单地完成此操作。首先,计算单词,然后按每个单词的出现次数和单词本身排序:

    from collections import Counter
    
    # Load the file and extract the words
    lines = open("gettysburg_address.txt").readlines()
    words = [ w for l in lines for w in l.rstrip().split() ]
    print 'Words in text:', len(words)
    
    # Use counter to get the counts
    counts = Counter( words )
    
    # Sort the (word, count) tuples by the count, then the word itself,
    # and output the k most frequent
    k = 4
    print 'Frequent words:'
    for w, c in sorted(counts.most_common(k), key=lambda (w, c): (c, w), reverse=True):
        print '%s %s' % (w, c)
    

    输出:

    Words in text: 278
    Frequent words:
    that 13
    the 9
    we 8
    to 8
    

    【讨论】:

    • 您可以尝试自己运行它!我试图为您提供一种更简洁的替代解决方案来解决此问题。
    • 我知道并且很欣赏这一点,但它必须像我的代码一样以某种方式格式化。
    • 您能否修改您的问题以指定该格式?还是我错过了什么?
    • 而且它不应该按照你的方式打印出来。它应该像我的问题一样垂直打印。
    • 这就是我希望它发生的事情,但我确实需要它来打印出所有的单词。有什么办法可以在我的代码中添加一些内容以使其以这种方式打印吗?我不使用 from 和 import 函数。这有点太高级了。
    【解决方案3】:

    您为什么不断重新打开文件并创建新词典?你的代码需要做什么?

    create a new empty dictionary to store words {word: count}
    open the file
    work through each line (word) in the file
        if the word is already in the dictionary
            increment count by one
        if not
            add to dictionary with count 1
    

    那么你就可以很容易的得到字数了

    len(dictionary)
    

    以及n 最常用的单词及其计数

    sorted(dictionary.items(), key=lambda x: x[1], reverse=True)[:n]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2012-12-20
      • 1970-01-01
      相关资源
      最近更新 更多