【发布时间】:2020-11-06 19:09:52
【问题描述】:
我想提取在列表“单词”中找到元素的第一个实例。我下面的代码正确地做到了这一点。 但是对于列表“单词”中的某些项目(例如狗和猫),我想提取字符串的第一次出现,以及之后的 3 个句子 - 请有人能告诉我如何做到这一点吗?
我的代码如下:
text= 'the dog was there. the cat is there too. python is the best. she has a kitten. cat is cute. the dog want want want was there. my dog is a puppy. chocolate brownies. flower power.'
words=['dog', 'chocolate', 'cat' ,'flower']
lst=[]
for j in words:
for i in text.split('.'):
if j in i:
lst.append (i.split('.')[0])
break
else:
None
print(lst)
期望的输出:
['the dog was there. the cat is there too. python is the best' , 'chocolate brownies', 'the cat is there too. python is the best. she has a kitten', 'flower power']
我尝试过的(索引) - 不确定我做错了什么
if j[0] in i:
lst.append( i.split('.')[0:3]
if j[2] in i:
lst.append. i.split('.')[0:3]
谢谢
【问题讨论】:
-
你想要找到单词的句子 i,还是想要第一个句子 (0),如果你找到单词?
-
我要找到单词的第一个句子,然后对于一些元素,找到第一个句子+之后提取3个句子
-
@qwerty12 你如何确定哪些元素应该在之后提取 3 个句子?除非您知道这一点,否则不可能在单个 for 循环中完成您的要求。
-
是的,在这个例子中是它的狗和猫
标签: python python-3.x string list for-loop