循环遍历文件并单独保存

Loop through files and save them separately

我想遍历包含几千个文本文件的本地文件夹,删除停用词,然后将文件保存在子文件夹中。我的代码遍历所有文件,但将所有文本文件写入一个新文件中。我需要将文件分开 - 因为它们所在的位置,并且 完全相同的文件名 ,只是没有停用词。我做错了什么?

import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import glob
import os
import codecs

stop_words = set(stopwords.words('english'))

for afile in glob.glob("*.txt"):
    file1 = codecs.open(afile, encoding='utf-8')
    line = file1.read()
    words = word_tokenize(line)
    words_without_stop_words = [word for word in words if word not in stop_words]
    new_words = " ".join(words_without_stop_words).strip()
    appendFile = open('subfolder/file1.txt','w', encoding='utf-8')
    appendFile.write(new_words)
    appendFile.close()

我看到文件名将是 "file1"(第 11 行)- 我只是无法理解 glob(如果 glob 是解决方案?)。

原因是您在循环中使用了相同的名称。您应该在每次迭代中更改文件名。例如你可以试试这个:

counter = 0 # This line added
for afile in glob.glob("*.txt"):
    file1 = codecs.open(afile, encoding='utf-8')
    line = file1.read()
    words = word_tokenize(line)
    words_without_stop_words = [word for word in words if word not in stop_words]
    new_words = " ".join(words_without_stop_words).strip()
    appendFile = open('subfolder/file1' + str(counter) + ".txt",'w', encoding='utf-8') # This line changed
    appendFile.write(new_words)
    appendFile.close()
    counter += 1 # This line added

这里发生的事情是:我们添加了一个计数器变量,并将该数字添加到每个文件的名称末尾。

在循环结束时我们增加counter来分隔文件。

您可以尝试不同的方法,例如在新文件名的末尾添加原始文件名。

快速解决方案:

import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import glob
import os
import codecs

stop_words = set(stopwords.words('english'))

for afile in glob.glob("*.txt"):
    file1 = codecs.open(afile, encoding='utf-8')
    line = file1.read()
    words = word_tokenize(line)
    words_without_stop_words = [word for word in words if word not in stop_words]
    new_words = " ".join(words_without_stop_words).strip()

    subfolder = getSubfolder(afile)
    filename = getFilename(afile)
    appendFile = open('{}/{}.txt'.format(subfolder,filename),'w', encoding='utf-8')
    appendFile.write(new_words)
    appendFile.close()

我从来没有使用过 glob 或编解码器,我相信你的问题出在最后 3 行代码上。您使用常量字符串 ('subfolder/file1.txt') 作为最终文件目标 - 这就是您的结果落在一个文件中的原因。我用两个变量替换了目标路径。我从函数 "getSubfolder()" 和 "getFilename()" 中获得这些变量。您必须实现这些功能才能获得所需的文件名。

如果我理解你的目标是正确的,你的文件名保持不变,只是在不同的文件夹中。然后你可以使用这一行:

    appendFile = open('{}/{}.txt'.format('mysubfolder',afile),'w', encoding='utf-8')

边学边解:

我建议您看一下 https://github.com/inducer/pudb 并跟踪循环中每一步的执行情况。通过这种方式,您将看到并了解 python 做了什么,什么变量在某个时间点有什么值,等等。