我有一个列表如下。
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
