如何把一个txt文件里面的词汇用停用词洗掉

想把text中的停用词洗掉,然后存到log.txt里面

path = 'C://Users//Wang Ming//Desktop//毕业论文//素材//奥克朗//'

text = open( path +'奥克朗词云.txt',encoding='utf-8').read()

stopwords = open('C://Users//Wang Ming//Desktop//毕业论文//素材//停用词.txt')

log = open(path+"oak_pureword.txt",mode='a+',encoding="utf-8")

for i in stopwords:
    text = text.replace(i, "")

print(text,file=log)
log.close()

虽然运行成功了,但是log里面还是text里的原本内容,没有被stop掉,感觉replace函数没有起作用?

参考GPT和自己的思路:根据你的代码,问题出在你没有对停用词文件进行读取和处理。你需要将停用词存入列表中,并且去除换行符才能使你的代码正常工作。你可以按照下面修改你的代码:

path = 'C://Users//Wang Ming//Desktop//毕业论文//素材//奥克朗//'

text = open(path + '奥克朗词云.txt', encoding='utf-8').read()

stopwords_file = open('C://Users//Wang Ming//Desktop//毕业论文//素材//停用词.txt')
stopwords = []
for word in stopwords_file:
    word = word.strip() # 去除换行符
    stopwords.append(word)

log = open(path + "oak_pureword.txt", mode='a+', encoding="utf-8")

for i in stopwords:
    text = text.replace(i, "")

print(text, file=log)
log.close()

上面代码中,加了一个for循环来获取停用词列表,并且去除了换行符。这样你的代码就可以正常工作了。