[英]Run a Python Script for all the files in a directory
我的编程技能非常有限。 但是我有这个小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
等,但是我无法使其正常工作。我们非常感谢您的帮助。)
您提到的所有功能都应该可以迭代文件夹中的所有文件。 顺便说一句,当尝试使用那些方法( 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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.