繁体   English   中英

如何按字母顺序查找最常用的单词?

[英]How to find the most frequent words in alphabetical order?

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

例如,单词:“ that”是文本文件中最常见的单词。 因此,应首先打印:“ 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
>>>

一种简单的获取频率计数的方法是在内置收集模块中使用Counter类 它允许您传递单词列表,它将自动对所有单词进行计数并将每个单词映射到其频率。

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

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

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

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

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

您可以使用collection的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

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

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]

暂无
暂无

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

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