运行CSV目录列表并执行python脚本

运行CSV目录列表并执行python脚本,python,csv,nltk,glob,Python,Csv,Nltk,Glob,我有一个带有CSV的文件夹,我想在所有文件上运行相同的脚本,然后为每个带有相同名称的CSV输出一个文本。我知道你可以用操作系统和Glob来完成,但我对Python还相当陌生,还没有做过这种工作 下面是我用来清理CSV的脚本 import logging import csv import sys import simplejson from nltk.corpus import stopwords from collections import defaultdict stoplist = s

我有一个带有CSV的文件夹,我想在所有文件上运行相同的脚本,然后为每个带有相同名称的CSV输出一个文本。我知道你可以用操作系统和Glob来完成,但我对Python还相当陌生,还没有做过这种工作

下面是我用来清理CSV的脚本

import logging
import csv
import sys
import simplejson
from nltk.corpus import stopwords
from collections import defaultdict

stoplist = stopwords.words('dutch')


f = open('1949.csv') #changefilename here
csv_f = csv.reader(f, delimiter ='\t')
text_content = []

for row in csv_f:
    text_content.append(row[0])

#remove stopwords and tokenize
texts = [[word for word in document.lower().split() if word not in stoplist] for document in text_content]

newDoc = [[word for word in document if len(word) > 3 ]
        for document in texts]


f = open('output.txt', 'w')
simplejson.dump(newDoc, f)
f.close()

如何重写此脚本以运行CSV列表?

不确定我是否理解您的问题。 由于您提到操作系统并询问有关文件列表的信息,而不是仅询问一个文件,因此您可能正在寻找类似以下内容:

    filesInDir = os.listdir(<path_to_dir>)
    for fname in filesInDir:
        #<put your code in a function and do your CSV magic here>
        # when done, write to output
        name, extension = os.path.splitext(fname)
        outputTxt = name + '.txt'
        f = open(outputTxt, 'w')
        simplejson.dump(newDoc, f)
        f.close()
您可能希望包括一些检查,以确保您正在传递csv,而不是传递到os.listdir的文件夹中的任何其他文件


不确定这是否是您想要的…?

如果您使用Python2.6或更高版本,simplejson可以替换为json模块:。