首页 > 解决方案 > Python仅查找字符串中单词的第一个实例

问题描述

Python的新手在这里。我想提取找到列表中单词的第一个实例的句子。目前,它正在提取所有包含单词“dog”和“cat”的字符串。我试过 (i.split('.')[0])了,但这也不起作用。有人可以帮忙吗?

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')

输出:

the dog was there

the cat is there too

the dog want want want was there

na

期望的输出:

the dog was there

the cat is there too

n/a (because choclate is not found)

谢谢你!

标签: pythonpython-3.xstringfor-loop

解决方案


无需对代码进行大量更改,您的输出可以通过在“单词”列表中使用“删除”来实现。

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            words.remove(j) # this will remove the matched element from your search list
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')

推荐阅读