[英]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.