【问题标题】:How do I remove stopwords from a list using a text file如何使用文本文件从列表中删除停用词
【发布时间】:2018-08-25 06:50:38
【问题描述】:

我正在尝试使用包含我自己的停用词的文本文件删除停用词,并尝试创建一个没有停用词的新列表。但是,新列表不会删除停用词。

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)

有修复它的想法吗?我必须列出文本文件中的所有停用词还是直接导入?

【问题讨论】:

  • 您为什么要在列表中使用close 方法? new_list.close()
  • 不好意思,stop_list的内容是什么?通过代码,如果 stop_list 上存在 stopwords_list 中的单词,您似乎想将其添加到 new_list 中。我没有看到删除...
  • 我试图将不在 myownstopwordst.txt 中的单词添加到 new_list。所以 new_list 中不应该有任何停用词。
  • return 语句破坏了你想要做的事情,它将在第一次循环迭代时停止,并且下一行不执行
  • 我删除了退货,但它打印出一个新列表,里面什么都没有?

标签: python editor


【解决方案1】:

这是接受多个变量的工作代码:

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 来指导你写一个清晰的问题

【讨论】:

  • 您好,谢谢,但是我尝试了打印出所有停用词的代码,但它也打印了新列表,其中仍然存在停用词?
  • @user10272359 是的,我已经更新了我的答案,只是删除了 print(stopwords_list) 行。我将其用于测试目的
  • 您好,抱歉,删除 print(stopwords_list) 仅有助于删除打印的列表。该功能仍然不起作用,因为使用该功能时,当我打印出新列表时,停用词仍然出现?
  • 是的,它正在按预期工作。但是, def remove_stopwords(*args) 中的星号是什么意思?我尝试更改为另一个参数,但它给了我一个位置参数?
  • @user10272359 *args 允许您将可变数量的参数传递给函数,因此在您的情况下,您可以将多个参数传递给函数。阅读此链接:pythontips.com/2013/08/04/args-and-kwargs-in-python-explained。如果有效,请接受答案:)
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 2011-05-03
  • 2015-04-11
  • 2013-01-22
  • 1970-01-01
  • 2019-10-01
  • 2021-12-22
  • 2021-03-21
相关资源
最近更新 更多