繁体   English   中英

使用索引或查找方法进行精确单词匹配-Python

[英]Exact word match using index or find method - python

我有一个字符串“ the then there”,我想搜索准确/完整的单词,例如,在这种情况下,“ the”仅出现一次。 但是使用index()或find()方法会认为出现了3次,因为它也与“ then”和“ there”部分匹配。 我喜欢使用这两种方法中的任何一种,可以通过任何方式对其进行调整?

>>> 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

要在大文本中查找精确/完整单词的第一个位置,请尝试使用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

首先使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM