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

时间:2016-09-02 19:36:39

标签: python sorting dictionary tuples sorted

我正在尝试编写一个程序,该程序将在文本文件中读取并输出最常见单词列表(现在代码为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()

4 个答案:

答案 0 :(得分:2)

使用collections.Counter类。

from collections import Counter

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

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

答案 1 :(得分: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]定义要显示的最常出现的字词数。

答案 2 :(得分: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

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

>>> 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

答案 3 :(得分: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)