【问题标题】:Remove an elements from the string if it contains a stopwords [duplicate]如果它包含停用词,则从字符串中删除一个元素[重复]
【发布时间】:2019-01-02 11:23:55
【问题描述】:

我有一个如下列表:

lst = ['for Sam', 'Just in', 'Mark Rich']

我正在尝试从包含stopwords 的字符串列表(字符串包含一个或多个单词)中删除一个元素。

由于列表中的第一个和第二个元素包含forin,它们是stopwords,它将返回

new_lst = ['Mark Rich'] 

我尝试了什么

from nltk.corpus import stopwords

stop_words = set(stopwords.words('english'))

lst = ['for Sam', 'Just in', 'Mark Rich']
new_lst = [i.split(" ") for i in lst]
new_lst = [" ".join(i) for i in new_lst for j in i if j not in stop_words]

这给了我如下输出:

['for Sam', 'Just in', 'Mark Rich', 'Mark Rich']

【问题讨论】:

    标签: python python-3.x nltk


    【解决方案1】:

    你需要一个if 语句而不是额外的嵌套:

    new_lst = [' '.join(i) for i in new_lst if not any(j in i for j in stop_words)]
    

    如果你想使用set,你可以使用set.isdisjoint

    new_lst = [' '.join(i) for i in new_lst if stop_words.isdisjoint(i)]
    

    这是一个演示:

    stop_words = {'for', 'in'}
    
    lst = ['for Sam', 'Just in', 'Mark Rich']
    new_lst = [i.split() for i in lst]
    new_lst = [' '.join(i) for i in new_lst if stop_words.isdisjoint(i)]
    
    print(new_lst)
    
    # ['Mark Rich']
    

    【讨论】:

    • 您的第一个答案就像一个魅力,但第二个答案是一个空列表。
    • @Sociopath,不,工作正常,看我的例子。
    【解决方案2】:

    您可以使用列表推导并使用sets 来检查两个列表中的任何单词是否相交:

    [i for i in lst if not set(stop_words) & set(i.split(' '))]
    ['Mark Rich']]
    

    【讨论】:

    • 谢谢。像魅力一样工作。只有一件事,在你的回答中你放错了]
    • 注意set.intersectionset.disjoint 具有更高的复杂性。无需计算 2 个集合的确切交集即可知道交集是否为空。
    • 是的,当我看到你的回答时,我真的想到了.isdisjoint。谢谢澄清
    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多