Python 不使用nltk语料库删除停止词
我试图在不使用nltk的情况下删除文本文件中的停止字。我有f1、f2、f3三个文本文件。f1逐行显示文本,f2显示停止词列表,f3为空文件。 我想逐行逐字地阅读f1,需要检查它是否在f2(停止字)中。如果单词不在停止词中,则将单词写在f3中。 因此,f3末尾的文字应与f1相同,但在每一行中,f2中的文字(停止字)应删除Python 不使用nltk语料库删除停止词,python,python-2.7,text-mining,Python,Python 2.7,Text Mining,我试图在不使用nltk的情况下删除文本文件中的停止字。我有f1、f2、f3三个文本文件。f1逐行显示文本,f2显示停止词列表,f3为空文件。 我想逐行逐字地阅读f1,需要检查它是否在f2(停止字)中。如果单词不在停止词中,则将单词写在f3中。 因此,f3末尾的文字应与f1相同,但在每一行中,f2中的文字(停止字)应删除 f1 = open("file1.txt","r") f2 = open("stop.txt","r") f3 = open("file2.txt","w") for line
f1 = open("file1.txt","r")
f2 = open("stop.txt","r")
f3 = open("file2.txt","w")
for line in f1:
words = line.split()
for word in words:
t=word
for line in f2:
w = line.split()
for word in w:
t1=w
if t!=t1:
f3.write(word)
f1.close()
f2.close()
f3.close()
这个代码是错误的。但是,任何人都可以通过更改代码来完成此任务
提前感谢。我个人要做的是循环浏览停止词列表(f2),并将每个词附加到脚本中的列表中。例:
stoplist = []
file1 = open('f1.txt','r')
file2 = open('f2.txt','r')
file3 = open('f3.txt','a') # append mode. Similar to rw
for line in f2:
w = line.split()
for word in w:
stoplist.append(word)
#end
for line in file1:
w = line.split()
for word in w:
if word in stoplist: continue
else:
file3.write(word)
#end
file1.close()
file2.close()
file3.close()
您的第一个for循环是错误的,因为通过此命令,
for words in words:t=word
您在t中没有所有单词,单词是一个列表,您可以使用它:此外,如果您的文件包含多行,则您的列表不包含所有单词。!!你必须这样做!它工作正常
f1 = open("a.txt","r")
f2 = open("b.txt","r")
f3 = open("c.txt","w")
first_words=[]
second_words=[]
for line in f1:
words = line.split()
for w in words:
first_words.append(w)
for line in f2:
w = line.split()
for i in w:
second_words.append(i)
for word1 in first_words :
for word2 in second_words:
if word1==word2:
first_words.remove(word2)
for word in first_words:
f3.write(word)
f3.write(' ')
f1.close()
f2.close()
f3.close()
您可以使用LinuxSed方法删除停止字
sed -f <(sed 's/.*/s|\\\<&\\\>||g/' stopwords.txt) all_lo.txt > all_remove1.txt
sed-f all_remove1.txt
您的井网!我很高兴!但你为什么要勾选上面的答案?!:)