【问题标题】:Run a Python Script for all the files in a directory为目录中的所有文件运行 Python 脚本
【发布时间】:2018-11-22 13:50:36
【问题描述】:

我的编程技能非常有限(x10)。 但我有这个小python脚本:

#load data
files = '/Users/xxx/Desktop/Test_SP/a.txt'
file = open(files, 'rt')
text = file.read()
file.close()
# split into words
from nltk.tokenize import word_tokenize
tokens = word_tokenize(text)
# stemming of words
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
stemmed = [porter.stem(word) for word in tokens]
print(stemmed[:20])

谁能告诉我如何为 此目录中的所有文件 (/Users/xxx/Desktop/Test_SP) 运行此脚本,而不仅仅是一次运行 1 个文件 (a.txt)

(我已经知道 glob、os.walk 等,但我无法让它发挥作用。非常感谢每一个帮助。)

【问题讨论】:

  • 您一次想要一个文件,或者合并所有文件中的文本,然后进行标记化或词干化?
  • 我一次想要一个文件。实际上我有第二个问题 - >我用“print(stemmed [:X])”得到输出 - 但我实际上希望程序:打开目录中的每个.txt文件 - >做东西 - >用重写每个.txt文件新的输出。

标签: python loops directory nltk stemming


【解决方案1】:

您提到的所有功能都应该适用于迭代文件夹中的所有文件。顺便说一句,尝试使用这些方法(globos.walk 等)运行时,您的错误是什么。 这是我使用listdir 的解决方案:

import os
files_path = '/Users/xxx/Desktop/Test_SP/'
for filename in os.listdir(files_path):
    # only care the txt files
    if filename.endswith(".txt"):
        #load data
        file = open("{}/{}".format(files_path,filename))
        text = file.read()
        file.close()
        # split into words
        from nltk.tokenize import word_tokenize
        tokens = word_tokenize(text)
        # stemming of words
        from nltk.stem.porter import PorterStemmer
        porter = PorterStemmer()
        stemmed = [porter.stem(word) for word in tokens]
        # write on the same file with input
        with open("{}/{}".format(files_path,filename), 'w') as fout:
            fout.write(stemmed[:20])

【讨论】:

  • 天哪,非常感谢你!!!!它的工作我不敢相信!过去几天我一直在尝试这样做,但我的编程经验接近于零(尽管我对学习非常感兴趣)->你是否也有我的第二个问题的解决方案->我得到了输出“打印( stemmed[:X])" - 但我实际上希望程序:打开目录中的每个 .txt 文件 -> 做一些事情 -> 用新输出重写每个 .txt 文件。
  • 嗨@patricks,我编辑了我的答案,用新的输出重写了同一个文件。我希望它有效,如果发现错误,请告诉我,干杯!
  • 哇,感谢您的努力!我现在收到以下错误: Traceback(最近一次调用最后一次):文件“/Users/xxx/Desktop/stemmer_small.py”,第 19 行,在 fout.write(stemmed[:20]) TypeError: write () 参数必须是 str,而不是 list。 (也许我忘了说这个,但如果我保持“stemmed [:20]”它只会占用每个 .txt 文件的前 20 个单词 -> 但我需要整个文本文件
  • 如何将 write 函数改为 writelines,类似于 fout.writelines(stemmed) ,writelines 将帮助您在文件上编写列表,但如果失败,您可以使用 for 循环对其进行迭代来编写它。
猜你喜欢
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 2019-02-04
相关资源
最近更新 更多