python - 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)
谢谢你!
解决方案
无需对代码进行大量更改,您的输出可以通过在“单词”列表中使用“删除”来实现。
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')
推荐阅读
- c++ - 使用 std::for_each 迭代和打印 std::map
- html - HTML 表格未按我希望的那样出现
- r - 网络在 R Fantasy Premier League 中抓取表格
- html - 在图像中显示的 Wordpress 问题
- python - TclError:Kaggle 中没有显示名称和 $DISPLAY 环境变量
- r - R - 加入列后ggplotly抛出错误
- javascript - (Javascript 和 Html)函数执行另一个未被告知执行的函数
- c# - C# Parallel Foreach 重复方法
- ios - 有没有更好的方法来排除 tvOS 的 navigationBarTitle?
- ios - 如何在下一个屏幕的自定义表格视图单元格中显示多个选定的行