为目录中的所有文件运行Python脚本

为目录中的所有文件运行Python脚本,python,loops,directory,nltk,stemming,Python,Loops,Directory,Nltk,Stemming,我的编程技能非常有限。 但我有一个小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 fro

我的编程技能非常有限。 但我有一个小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
)运行此脚本,而不是一次只运行一个文件(
a.txt


(我已经知道glob、
os.walk
等,但我无法让它工作。非常感谢您的帮助。)

您提到的所有功能都应该用于迭代文件夹中的所有文件。顺便说一句,当您尝试使用这些方法运行时(
glob
os.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])

你想要一次一个文件,或者合并所有文件中的文本,然后进行标记化或词干分析?我想要一次一个文件。事实上,我还有第二个问题->我用“print(stemmed[:X])”获得输出-但我实际上希望程序:打开目录中的每个.txt文件->做一些事情->用新的输出重写每个.txt文件。天哪,非常感谢!!!!我真不敢相信它能起作用!!!在过去的几天里,我一直在尝试这样做,但我几乎没有编程经验(不过我对学习非常感兴趣)->你是否也有解决我第二个问题的方法->我通过“print(stemmed[:X])获得输出-但我实际上希望程序:打开目录中的每个.txt文件->执行任务->用新输出重写每个.txt文件。嗨@patricks,我编辑了我的答案,用新输出重新写入相同的文件。我希望它能起作用,如果发现错误,请告诉我,干杯!哇,谢谢你的努力!我现在得到了以下错误:Traceback(最近一次调用last):File“/Users/xxx/Desktop/stemmer_small.py”,第19行,在fout.write(词干为[:20])类型错误:write()参数必须是str,而不是list。(也可能我忘了说这个,但如果我保持“词干[:20]”,它只需要每个.txt文件的前20个字->但我需要整个文本文件如何将write函数更改为writelines,类似于
fout.writelines(词干化)
,writelines将帮助您在文件上编写列表,但如果失败,您可以使用for循环对其进行迭代来编写。