【发布时间】:2019-01-24 06:17:30
【问题描述】:
我想从本地文件夹中的多个文件中删除停用词。我知道如何为一个文件执行此操作,但我无法为该文件夹中的所有文件执行此操作。
我尴尬的尝试:
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 = open(afile)
line = file1.read()
words = word_tokenize(line)
words_without_stop_words = ["" if word in stop_words else word for word in words]
new_words = " ".join(words_without_stop_words).strip()
appendFile = open('subfolder/file1.txt','w')
appendFile.write(new_words)
appendFile.close()
我什至不知道我能走多远,因为我明白了:
Traceback(最近一次调用最后一次): 文件“C:\Desktop\neg\sw.py”,第 14 行,在 行 = file1.read() 解码中的文件“C:\Program Files\Python36\lib\encodings\cp1252.py”,第 23 行 返回 codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError:“charmap”编解码器无法解码位置 1757 中的字节 0x9d:字符映射到
<undefined>
我尝试使用 glob,但找不到好的文档。也许没有必要?
【问题讨论】:
-
我认为至少你应该使用
open('subfolder/file1.txt','a'),因为'w'会导致你每次使用它时覆盖文件。我假设您将所有非停用词存储在同一个文件中。 -
很高兴显示错误消息,但最好提供完整的堆栈跟踪以了解在哪一行引发了错误。而当涉及到编码问题时,您还应该说出确切的Python版本和操作系统。
-
错误信息表明输入文件不是Unicode文件。如果没有看到错误周围的各个字节,我们就无法猜测它是什么。请参阅Stack Overflow
character-encodingtag info page,了解一些疑难解答提示和有关如何发布良好、定义明确的问题的说明。 -
@SergeBallesta 更新了错误。
标签: python python-3.x