我正在尝试使用包含我自己的停用词的文本文件删除停用词,并尝试创建一个没有停用词的新列表。但是,新列表不会删除停用词。
def remove_stopwords(parametera):
stopwords = open('myownstopwords.txt')
stopwords_list = stopwords.readlines()
new_list = []
for parametera in stopwords_list:
if parametera not in stop_list:
new_list.append(parametera)
stopwords.close()
new_list.close()
print(new_list)
有任何修复建议吗?我是否必须列出文本文件中的所有停用词,还是可以将其导入?
答案 0 :(得分:2)
以下是可接受多个变量的工作代码:
def remove_stopwords(*args):
with open('myownstopwords.txt','r') as my_stopwords:
stopwords_list = my_stopwords.read()
new_list = []
for arg in args:
if str(arg) not in stopwords_list:
new_list.append(arg)
else:
pass # You can write something to do if the stopword is found
my_stopwords.close()
print(new_list)
remove_stopwords('axe','alien','a')
这是只有一个变量的代码:
def remove_stopwords(param):
with open('myownstopwords.txt','r') as my_stopwords:
stopwords_list = my_stopwords.read()
new_list = []
if str(param) not in stopwords_list:
new_list.append(param)
else:
pass # You can write something to do if the stopword is found
my_stopwords.close()
print(new_list)
remove_stopwords('axe')
接受列表的代码:
def remove_stopwords(params):
with open('myownstopwords.txt','r') as my_stopwords:
stopwords_list = my_stopwords.read()
new_list = []
for param in params:
if str(param) not in stopwords_list:
new_list.append(param)
else:
pass # You can write something to do if the stopword is found
my_stopwords.close()
print(new_list)
remove_stopwords(['axe','a'])
我删除了多余的return
语句和new_list.close()
,因为无法关闭列表并摆脱了for
循环。
编辑:对于支持列表,我刚刚添加了一个for循环以遍历提供的参数列表
欢迎来到stackoverflow!请在以后写问题时,明确要实现的目标,并包括链接到查询的所有变量和源。
我建议您阅读this,以指导您写出清晰的问题