我有两个包含完整句子和短语的列表:

my_sentence=['This is string', 'This is string too', 'That is not string', 'That are not sentence']
my_phrase=['This is', 'That is']

我试着在my_sentence中找到包含my_phrase的字符串.对于匹配的句子,我用my_phrase来拆分句子,并将其余的句子放在另一个列表中,假设是my_result.但是,我也想保存my_result中不匹配的句子.

my_result年的预期结果是:

my_result=['string','string too', 'not string', 'That are not sentence'] 

我试过这个代码:

result=[]
for sentence in my_sentence:
  for phrase in my_phrase:
    if phrase in sentence:
            res=sentence.split(phrase)
            result.append(res)
    else:
      res=sentence
      result.append(res)

print(result)

然而,我得到了这样的结果:

[['', ' string'], 'This is string', ['', ' string too'], 'This is string too', 'That is not string', ['', ' not string'], 'That are not sentence', 'That are not sentence']

有人能帮我修正一下我的代码吗?

提前谢谢您.

推荐答案

您可以try 使用re模块:

import re

my_sentence = [
    "This is string",
    "This is string too",
    "That is not string",
    "That are not sentence",
]

my_phrase = ["This is", "That is"]

pat = re.compile("|".join(map(re.escape, my_phrase)))

out = [pat.sub("", s).strip() for s in my_sentence]
print(out)

打印:

['string', 'string too', 'not string', 'That are not sentence']

Python-3.x相关问答推荐

如何立即从asyncio.Task获取异常?

如何通过 python 使用 auth no priv 获取 SNMPv3?

使用 Python 在特定组的列中设置上限

Pandas 窗口聚合两个排序表

多进程:两个进程,一起杀死

SMTP 库 Python3:不太安全的应用程序访问

如何将虚拟变量列转换为多列?

判断是否存在大文件而不下载它

ImportError:没有名为资源的模块

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

在 jupyter notebook 的单元格中使用 sudo

Pytorch 的随机 Select ?

django.core.exceptions.ImproperlyConfigured

如何使用 d.items() 更改 for 循环中的所有字典键?

从大字典中弹出 N 项的最快方法

类方法和实例方法同名

计数大于Pandas groupby 中的值的项目

为什么在 Python 3 中实例的 __dict__ 的大小要小得多?

为什么异步库比这个 I/O 绑定操作的线程慢?

有没有办法在多个线程中使用 asyncio.Queue ?