我正在尝试处理一个普通的文本文件,并从另一个包含要去除词汇的文件(停用词文件)中删除确定的单词,这些单词由回车符("\n")分隔。
目前我将两个文件都转换为列表,以便可以比较每个列表的元素。我有一个函数可以工作,但它不能删除我在停用词文件中指定的所有单词。非常感谢您的任何帮助。
目前我将两个文件都转换为列表,以便可以比较每个列表的元素。我有一个函数可以工作,但它不能删除我在停用词文件中指定的所有单词。非常感谢您的任何帮助。
def elimstops(file_str): #takes as input a string for the stopwords file location
stop_f = open(file_str, 'r')
stopw = stop_f.read()
stopw = stopw.split('\n')
text_file = open('sample.txt') #Opens the file whose stop words will be eliminated
prime = text_file.read()
prime = prime.split(' ') #Splits the string into a list separated by a space
tot_str = "" #total string
i = 0
while i < (len(stopw)):
if stopw[i] in prime:
prime.remove(stopw[i]) #removes the stopword from the text
else:
pass
i += 1
# Creates a new string from the compilation of list elements
# with the stop words removed
for v in prime:
tot_str = tot_str + str(v) + " "
return tot_str
stopw
并从prime
中删除元素。 - Sam Mussmann