【问题标题】:how to filter out words in python? [duplicate]如何过滤掉python中的单词? [复制]
【发布时间】:2012-11-19 08:45:25
【问题描述】:

例如:

item =['the dog is gone', 'the dog and cat is gone']
words= ['dog','cat'] 

我希望能够过滤掉dog 和cat,所以它会显示为:

item=['the  is gone', 'the   and  is gone']

item1=[] 
for w in words:
   for line in item:
      if w in line:
         j=gg.replace(it,'')
         item1.append(j)

我得到以下信息:

['the  is gone', 'the cat and  is gone', 'the  and dog is gone']

【问题讨论】:

    标签: python string sorting


    【解决方案1】:

    您可以改用这种方法:

    item =['the dog is gone', 'the dog and cat is gone']
    words= ['dog','cat'] 
    
    item2 = [" ".join([w for w in t.split() if not w in words]) for t in item]
    
    print item2
    
    >>> ['the is gone', 'the and is gone']
    

    【讨论】:

    • 这明显更快!我的用例的微秒与毫秒
    【解决方案2】:

    您正在遍历每个单词的所有行并附加替换。你应该切换这些循环:

    item1 = [] 
    for line in item:
        for w in words:
            line = line.replace(w, '')
        item1.append(line)
    

    注意:我修改了一些代码

    • 将gg 更改为line
    • 将it 更改为item
    • 删除了检查line 是否包含w,因为它由replace 处理

    replace 不知道单词边界。如果您只想删除整个单词,您应该尝试不同的方法。使用re.sub

    import re
    
    item1 = [] 
    for line in item:
        for w in words:
            line = re.sub(r'\b%s\b' % w, '', line)  # '\b' is a word boundry
        item1.append(line)
    

    【讨论】:

    • 什么时候做这个其他的话它会分开的话,即。好 -> od 但 go==good 给出了错误的比较。
    • @user1753878 更新了答案,只替换了完整的单词
    猜你喜欢
    • 2014-04-07
    • 2014-03-31
    • 1970-01-01
    • 2015-06-26
    • 2019-07-16
    • 1970-01-01
    • 2014-09-01
    • 2020-11-12
    • 2011-11-12
    相关资源
    最近更新 更多