使用索引或查找方法的精确单词匹配 - python

时间:2016-11-15 06:45:14

标签: python indexing find

我有一个字符串"然后那里"我想搜索确切/完整的单词,例如在这种情况下""只出现一次。但是使用index()或find()方法认为它出现了三次,因为它与"然后"和"那里"太。我喜欢使用这些方法中的任何一种,我可以通过任何方式调整它们来工作吗?

>>> s = "the then there"
>>> s.index("the")
0
>>> s.index("the",1)
4
>>> s.index("the",5)
9
>>> s.find("the")
0
>>> s.find("the",1)
4
>>> s.find("the",5)
9

2 个答案:

答案 0 :(得分:2)

要在大文字中找到完全/完整单词的第一个位置,请尝试使用re.search()match.start()函数应用以下方法:

import re

test_str = "when we came here, what we saw that the then there the"
search_str = 'the'
m = re.search(r'\b'+ re.escape(search_str) +r'\b', test_str, re.IGNORECASE)
if m:
    pos = m.start()
    print(pos)

输出:

36

https://docs.python.org/3/library/re.html#re.match.start

答案 1 :(得分:1)

首先使用str.split()将字符串转换为单词列表,然后搜索单词。

>>> s = "the then there"
>>> s_list = s.split() # list of words having content: ['the', 'then', 'there']
>>> s_list.index("the")
0
>>> s_list.index("then")
1
>>> s_list.index("there")
2
相关问题