首页 > 解决方案 > 从多个文件中删除停用词 (NLTK)

问题描述

我有几个 tousend 文本文件(本地文件夹),并希望从该文件夹中的每个文件中删除停用词并将新文件保存在子文件夹中。

一个文件的代码:

import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

stop_words = set(stopwords.words('english'))
file1 = open("1_1.txt")
line = file1.read()
words = line.split()
for r in words:
    if not r in stop_words:
        appendFile = open('subfolder/1_1.txt','a')
        appendFile.write(" "+r)
        appendFile.close()

我想我必须用 glob 试试?但我似乎不了解文档。我也许应该降低()文本?必须有一个超级简单的方法,但我只找到一个句子或一个文件的教程,而不是多个文件。

标签: pythonpython-3.xnltkstop-words

解决方案


import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

stop_words = set(stopwords.words('english'))
file1 = open("file1.txt")
line = file1.read()
words = word_tokenize(line)
words_witout_stop_words = ["" if word in stop_words else word for word in words]
new_words = " ".join(words_witout_stop_words).strip()
appendFile = open('subfolder/file1.txt','w')
appendFile.write(new_words)
appendFile.close()

现在你可以通过你的文件名添加一个循环localfolder,你很高兴。


推荐阅读