为了账号安全,请及时绑定邮箱和手机立即绑定

Python,循环遍历某个目录下的文件,统计词频,输出结果到txt

Python,循环遍历某个目录下的文件,统计词频,输出结果到txt

手掌心 2023-06-06 16:42:20
我拼凑了一些打开文本文件的工作 python,将其转换为小写,消除停用词,并输出文件中最常用词的列表:from collections import Counterfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizestop_words = set(stopwords.words('english'))file1 = open("ocr.txt")line = file1.read()words =  line.split()words = [word.lower() for word in words]for r in words:    if not r in stop_words:        appendFile = open('cleaned_output.txt','a')        appendFile.write(" "+r)        appendFile.close()with open("cleaned_output.txt") as input_file:    count = Counter(word for line in input_file                         for word in line.split())print(count.most_common(10), file=open('test.txt','a'))我想修改它以对目录中的所有文件执行相同的操作,并将结果输出到唯一的文本文件或作为 csv 中的行。我知道这os.path可能可以在这里使用,但我不确定如何使用。我真的很感激一些帮助。先感谢您!
查看完整描述

2 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

我将您的代码片段转换为一个函数,该函数将包含输入文件的文件夹的路径作为参数。以下代码获取指定文件夹中的所有文件,并为该文件夹中的每个文件生成 cleaned_output.txt 和 test.txt 到新创建的输出目录。输出文件在末尾附加了它们生成的输入文件的名称,以便更容易区分它们,但您可以更改它以满足您的需要。


from collections import Counter

from nltk.corpus import stopwords

from nltk.tokenize import word_tokenize

import os



path = 'input/'


def clean_text(path):

  try:

    os.mkdir('output')

  except:

    pass

  

  out_path = 'output/'


  files = [f for f in os.listdir(path) if os.path.isfile(path+f)]

  file_paths = [path+f for f in files]

  file_names = [f.strip('.txt') for f in files]

  

  for idx, f in enumerate(file_paths):

    stop_words = set(stopwords.words('english'))

    file1 = open(f)

    line = file1.read()

    words =  line.split()

    words = [word.lower() for word in words]

    print(words)


    for r in words:

        if not r in stop_words:

            appendFile = open(out_path + 'cleaned_output_{}.txt'.format(file_names[idx]),'a')

            appendFile.write(" "+r)

            appendFile.close()

    with open(out_path + 'cleaned_output_{}.txt'.format(file_names[idx])) as input_file:

        count = Counter(word for line in input_file

                            for word in line.split())


    print(count.most_common(10), file=open(out_path + 'test_{}.txt'.format(file_names[idx]),'a'))




clean_text(path)

这是你要找的吗?


查看完整回答
反对 回复 2023-06-06
?
达令说

TA贡献1821条经验 获得超6个赞

您可以使用os.listdir获取目录中的所有文件。这将返回一个目录中所有项目的路径列表作为您可以迭代的字符串。



查看完整回答
反对 回复 2023-06-06
  • 2 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信