python - 如何过滤掉python中的单词?

标签 python string sorting

<分区>

例如:

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

我希望能够过滤掉 dogcat 所以它会显示为:

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']

最佳答案

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

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)

关于python - 如何过滤掉python中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13656925/

相关文章:

python - 拦截用于记录的 Django 500 错误,而不创建/提供自定义 500.html

c++ - 将 std::__cxx11::string 转换为 std::string

c++ - 序列化哪里出错了?

PHP/MySQL : querying MySQL with an array and getting results in an array

c - 根据长度崩溃对静态数组中的字符串进行排序? |错误分配/访问|

python - Pandas 从数据帧中删除镜像对

python - pyPdf IndirectObject in/Rotate

c - 对链表进行排序时出现段错误

python - 类中的文档字符串或 __init__ 构造函数?

c - 我需要为 50 个字符的 X 字符串数组分配多少内存?