如何在python中的500个文本文件中找到500个最常用的单词?

时间:2015-01-03 13:28:15

标签: python python-2.7 text-processing

我在一个目录中有500个文本文件。我必须在所有文本文件中找到500个最常用的单词。我怎样才能实现呢?

PS:我已经搜索了很多但找不到解决方案。

4 个答案:

答案 0 :(得分:4)

使用collections.Counter

import os
from collections import Counter

c, directory = Counter(), 'path_to_your_directory'

for x in os.listdir(directory):
    fname = os.path.join(directory, x)
    if os.path.isfile(fname):
        with open(fname) as f:
            c += Counter(f.read().split())

for word, _ in c.most_common(500):
    print(word)

当然,它会读取该目录中的每个文件。如果这不是预期的行为,请使用glob.glob or glob.iglob所需的模式而不是os.listdir(请参阅Reut对我的回答的评论)。

答案 1 :(得分:1)

这是我可以考虑使用字典进行计数的最简单的方法,使用键作为单词ad计算值:

import os
# word counts are stored in a dictionary
# for fast access and duplication prevention
count = {}
# your text files should be in this folder
DIR = "files"
# iterate over all files in the folder
for filename in os.listdir(DIR):
    with open(os.path.sep.join([DIR, filename]), 'r') as f:
        for line in f.readlines():
            # strip line separators from end of line
            line = line.strip()
            # once we have a line from the file, split it to words, and
            # add word to the scores (if it's new), or increase it's count
            for word in line.split():
                if word in count:
                    # existing
                    count[word] = count[word] + 1
                else:
                    # new
                    count[word] = 1
print sorted(count.items(), key=lambda x: x[1], reverse=True)[:500]

使用collections.Counter(如Padraic建议的那样):

import os
from collections import Counter

count = Counter()
DIR = "files"
for filename in os.listdir(DIR):
    with open(os.path.sep.join([DIR, filename]), 'r') as f:
        for line in f.readlines():
            line = line.strip()
            # count all words in line
            count.update(line.split())
print count.most_common(500)

答案 2 :(得分:0)

您可以为每个新单词和一个单词数组创建一个计数器。将每个新单词添加到数组中。使用"索引"将文本文件中的每个单词与数组中的单词进行比较,递增单词的计数器。或者你可以创建一个数组,填充每个NEW  从文本文件中的单词,使用数组的第二个元素作为计数器。

答案 3 :(得分:0)

我们可以使用集合模块中的Counter方法。

  1. glob
  2. 只读目标目录中的文本文件
  3. 通过for loop迭代步骤1中的所有文件。
  4. 通过with语句和read()文件对象方法以读取模式打开文件。
  5. split()字符串方法拆分文件内容,并使用Counter创建可数字典。添加两个计数器。 https://docs.python.org/2/library/collections.html
  6. 通过most_common(3)方法从计数器中获取最常用的字词。
  7. 代码:

    from glob import glob 
    from  collections import Counter
    
    p = "/home/vivek/Desktop/test/*.txt"
    main_counter = Counter()
    
    for i in glob(p):
        with open(i, "rb") as fp:
            main_counter += Counter(fp.read().split())
    
    print "main_counter:-", main_counter
    print "most common 3:-", main_counter.most_common(3)
    

    输出: -

    vivek@vivek:~/Desktop$ python 4.py 
    main_counter:- Counter({'This': 3, 'try': 2, 'again.': 2, 'is': 2, 'can': 2, 'file': 2, 'you': 2, 'my': 2, '1': 1, 'this': 1, '2': 1})
    most common 3:- [('This', 3), ('try', 2), ('again.', 2)]