gpt4 book ai didi

python - 查表并在python中拆分句子

转载 作者:太空宇宙 更新时间:2023-11-04 08:37:15 25 4
gpt4 key购买 nike

我有一个列表如下。

mylist = ['test copy', 'test project', 'test', 'project']

我想看看我的句子是否包括前面提到的 mylist元素并从第一个匹配中拆分句子并获得其第一部分。

例如:

mystring1 = 'it was a nice test project and I enjoyed it a lot'

输出应该是:it was a nice

mystring2 = 'the example test was difficult'

输出应该是:the example

我目前的代码如下。

for sentence in L:
if mylist in sentence:
splits = sentence.split(mylist)
sentence= splits[0]

但是,我收到一条错误消息 TypeError: 'in <string>' requires string as left operand, not list .有办法解决这个问题吗?

最佳答案

您需要另一个 for 循环来遍历 mylist 中的每个字符串。

mylist = ['test copy', 'test project', 'test', 'project']
mystring1 = 'it was a nice test project and I enjoyed it a lot'
mystring2 = 'the example test was difficult'

L = [mystring1, mystring2]
for sentence in L:
for word in mylist:
if word in sentence:
splits = sentence.split(word)
sentence= splits[0]
print(sentence)
# it was a nice
# the example

关于python - 查表并在python中拆分句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48059490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com