【问题标题】:Python - Finding word frequencies of list of words in text filePython - 查找文本文件中单词列表的单词频率
【发布时间】:2013-02-02 00:08:51
【问题描述】:

我正在尝试加快我的项目以计算词频。我有 360 多个文本文件,我需要获取单词总数和另一个单词列表中每个单词出现的次数。我知道如何使用单个文本文件来做到这一点。

>>> import nltk
>>> import os
>>> os.chdir("C:\Users\Cameron\Desktop\PDF-to-txt")
>>> filename="1976.03.txt"
>>> textfile=open(filename,"r")
>>> inputString=textfile.read()
>>> word_list=re.split('\s+',file(filename).read().lower())
>>> print 'Words in text:', len(word_list)
#spits out number of words in the textfile
>>> word_list.count('inflation')
#spits out number of times 'inflation' occurs in the textfile
>>>word_list.count('jobs')
>>>word_list.count('output')

单独获取“通货膨胀”、“工作”、“产出”的频率太繁琐了。我可以把这些词放到一个列表中,同时找出列表中所有词的出现频率吗?基本上 this 使用 Python。

示例:而不是这个:

>>> word_list.count('inflation')
3
>>> word_list.count('jobs')
5
>>> word_list.count('output')
1

我想这样做(我知道这不是真正的代码,这是我寻求帮助的内容):

>>> list1='inflation', 'jobs', 'output'
>>>word_list.count(list1)
'inflation', 'jobs', 'output'
3, 5, 1

我的单词列表将包含 10-20 个术语,因此我需要能够将 Python 指向单词列表以获取计数。如果输出能够复制+粘贴到 Excel 电子表格中,其中单词为列,频率为行,那也很好

例子:

inflation, jobs, output
3, 5, 1

最后,任何人都可以帮助为所有文本文件自动执行此操作吗?我想我只是将 Python 指向该文件夹,它可以从新列表中对 360 多个文本文件中的每一个进行上述字数计数。似乎很容易,但我有点卡住了。有什么帮助吗?

这样的输出会很棒: 文件名1 通货膨胀、就业、产出 3、5、1

Filename2
inflation, jobs, output
7, 2, 4

Filename3
inflation, jobs, output
9, 3, 5

谢谢!

【问题讨论】:

    标签: python text frequency


    【解决方案1】:
    import re, os, sys, codecs, fnmatch
    import decimal
    import zipfile
    import glob
    import csv
    
    path= 'C:\\Users\\user\\Desktop\\sentiment2020\\POSITIVE'
    
    files=[]
    for r,d,f in os.walk(path):
        for file in f:
            if'.txt' in  file:
                files.append(os.path.join(r,file))
    
    for f in files:
        print(f)
        file1= codecs.open(f,'r','utf8',errors='ignore')
        content=file1.read()
    
    words=content.split()
    for x in words:
        print (x)
    
    dicts=[]
    if __name__=="__main__":  
        str =words
        str2 = [] 
        for i in str:              
            if i not in str2: 
                  str2.append(i)  
        for i in range(0, len(str2)):
            a= {str2[i]:str.count(str2[i])}
            dicts.append(a)
    for i in dicts:        
        print(dicts)
    
    
    
    #  for i in range(len(files)):
      #    with codecs.open('C:\\Users\\user\\Desktop\\sentiment2020\\NEGETIVE1\\sad1%s.txt' % i, 'w',"utf8") as filehandle:
      #         filehandle.write('%s\n' % dicts) 
    

    【讨论】:

      【解决方案2】:

      一个计算文本文件中词频的简单功能代码:

      {
      import string
      
      def process_file(filename):
      hist = dict()
      f = open(filename,'rb')
      for line in f:
          process_line(line,hist)
      return hist
      
      def process_line(line,hist):
      
      line = line.replace('-','.')
      
      for word in line.split():
          word = word.strip(string.punctuation + string.whitespace)
          word.lower()
      
          hist[word] = hist.get(word,0)+1
      
      hist = process_file(filename)
      print hist
      }
      

      【讨论】:

        【解决方案3】:

        一种可能的实现方式(使用计数器)...

        我认为写入 csv 文件并将其导入 Excel 会更简单,而不是打印输出。查看http://docs.python.org/2/library/csv.html 并替换print_summary

        import os
        from collections import Counter
        import glob
        
        def word_frequency(fileobj, words):
            """Build a Counter of specified words in fileobj"""
            # initialise the counter to 0 for each word
            ct = Counter(dict((w, 0) for w in words))
            file_words = (word for line in fileobj for word in line.split())
            filtered_words = (word for word in file_words if word in words)
            return Counter(filtered_words)
        
        
        def count_words_in_dir(dirpath, words, action=None):
            """For each .txt file in a dir, count the specified words"""
            for filepath in glob.iglob(os.path.join(dirpath, '*.txt')):
                with open(filepath) as f:
                    ct = word_frequency(f, words)
                    if action:
                        action(filepath, ct)
        
        
        def print_summary(filepath, ct):
            words = sorted(ct.keys())
            counts = [str(ct[k]) for k in words]
            print('{0}\n{1}\n{2}\n\n'.format(
                filepath,
                ', '.join(words),
                ', '.join(counts)))
        
        
        words = set(['inflation', 'jobs', 'output'])
        count_words_in_dir('./', words, action=print_summary)
        

        【讨论】:

        • 我需要替换上面的哪些变量?我需要将我的特定目录放在哪里?
        • Rob,你能告诉我在上面的代码中我应该把我正在工作的目录文件夹和我感兴趣的单词列表放在哪里吗?我不确定我必须在您定义的 3 个函数中添加什么。
        • 要处理的目录的路径是函数count_words_in_dir()的第一个参数。请参阅代码的最后一行。您的目标词集是同一函数的第二个参数。见倒数第二行。
        【解决方案4】:

        如果我了解您的问题,collections.Counter() 已涵盖此内容。

        文档中的示例似乎与您的问题相符。

        # Tally occurrences of words in a list
        cnt = Counter()
        for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
            cnt[word] += 1
        print cnt
        
        
        # Find the ten most common words in Hamlet
        import re
        words = re.findall('\w+', open('hamlet.txt').read().lower())
        Counter(words).most_common(10)
        

        从上面的例子你应该可以做到:

        import re
        import collections
        words = re.findall('\w+', open('1976.03.txt').read().lower())
        print collections.Counter(words)
        

        EDIT天真的方法来展示一种方式。

        wanted = "fish chips steak"
        cnt = Counter()
        words = re.findall('\w+', open('1976.03.txt').read().lower())
        for word in words:
            if word in wanted:
                cnt[word] += 1
        print cnt
        

        【讨论】:

        • 我已经和 Counter 混了几个小时了,还是搞不定。
        • 上面的例子将给我统计我的文本文件中的所有唯一词(在我的例子中超过 3000 个唯一词)。我只需要文本文件中 10-20 个特定单词的计数。
        • 我认为这对列表有用,非常感谢!我盯着那个柜台页面看了好几个小时哈哈
        • 如果有用,请支持答案或勾选接受,以便其他人知道它有效。
        • @sotapme 我正在尝试做类似的事情,但我无法使用图书馆收藏。关于没有它如何完成的任何想法?
        猜你喜欢
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 2012-12-14
        • 1970-01-01
        • 2021-01-21
        相关资源
        最近更新 更多