尝试输出文本文件中x个最常用的单词

问题描述 投票:0回答:4

我正在尝试编写一个程序,该程序将读入文本文件并输出最常见的单词列表(现在代码编写为30)及其计数。像这样的东西:

word1 count1
word2 count2
word3 count3
...   ...
...   ...
wordn countn

按count1> count2> count3> ...> countn的顺序排列。这是我到目前为止,但我不能得到排序函数来执行我想要的。我现在得到的错误是:

TypeError: list indices must be integers, not tuple

我是python的新手。任何帮助,将不胜感激。谢谢。

 def count_func(dictionary_list):
  return dictionary_list[1]

def print_top(filename):
  word_list = {}
  with open(filename, 'r') as input_file:

    count = 0

    #best
    for line in input_file:
      for word in line.split():
        word = word.lower()
        if word not in word_list:
          word_list[word] = 1
        else:
          word_list[word] += 1

#sorted_x = sorted(word_list.items(), key=operator.itemgetter(1))
#  items = sorted(word_count.items(), key=get_count, reverse=True)

  word_list = sorted(word_list.items(), key=lambda x: x[1])

  for word in word_list:
    if (count > 30):#19
      break
    print "%s: %s" % (word, word_list[word])
    count += 1


# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()
python sorting dictionary tuples sorted
4个回答
2
投票

使用collections.Counter类。

from collections import Counter

for word, count in Counter(words).most_common(30):
    print(word, count)

一些未经请求的建议:在一切都作为一大块代码工作之前,不要制作这么多功能。在工作之后重构为函数。你甚至不需要这么小的脚本的主要部分。


1
投票

使用itertools'groupby

from itertools import groupby

words = sorted([w.lower() for w in open("/path/to/file").read().split()])
count = [[item[0], len(list(item[1]))] for item in groupby(words)]
count.sort(key=lambda x: x[1], reverse = True)
for item in count[:5]:
    print(*item)
  • 这将列出文件的单词,对它们进行排序并列出唯一的单词及其出现。随后,找到的列表按出现次数排序: count.sort(key=lambda x: x[1], reverse = True)
  • reverse = True首先列出最常用的单词。
  • 在线: for item in count[:5]: [:5]定义了要显示的最常出现的单词的数量。

0
投票

第一种方法正如其他人所建议的那样,即使用most_common(...)根据你的需要不起作用,因为它返回第n个最常见的单词,而不是其计数小于或等于n的单词:

这是使用most_common(...):注意它只打印第n个最常见的单词:

>>> import re
... from collections import Counter
... def print_top(filename, max_count):
...     words = re.findall(r'\w+', open(filename).read().lower())
...     for word, count in Counter(words).most_common(max_count):
...         print word, count
... print_top('n.sh', 1)
force 1

正确的方法如下,注意它打印所有计数小于等于count的单词:

>>> import re
... from collections import Counter
... def print_top(filename, max_count):
...     words = re.findall(r'\w+', open(filename).read().lower())
...     for word, count in filter(lambda x: x[1]<=max_count, sorted(Counter(words).items(), key=lambda x: x[1], reverse=True)):
...         print word, count
... print_top('n.sh', 1)
force 1
in 1
done 1
mysql 1
yes 1
egrep 1
for 1
1 1
print 1
bin 1
do 1
awk 1
reinstall 1
bash 1
mythtv 1
selections 1
install 1
v 1
y 1

0
投票

这是我的python3解决方案。我在接受采访时被问到这个问题,面试官很高兴这个解决方案,尽管在时间限制较少的情况下,上面提供的其他解决方案对我来说似乎更好。

    dict_count = {}
    lines = []

    file = open("logdata.txt", "r")

    for line in file:# open("logdata.txt", "r"):
        lines.append(line.replace('\n', ''))

    for line in lines:
        if line not in dict_count:
            dict_count[line] = 1
        else:
            num = dict_count[line]
            dict_count[line] = (num + 1)

    def greatest(words):
        greatest = 0
        string = ''
        for key, val in words.items():
            if val > greatest:
                greatest = val
                string = key
        return [greatest, string]

    most_common = []
    def n_most_common_words(n, words):
        while len(most_common) < n:
            most_common.append(greatest(words))
            del words[(greatest(words)[1])]

    n_most_common_words(20, dict_count)

    print(most_common)
© www.soinside.com 2019 - 2024. All rights reserved.