如何在Python中查找字符串中精确单词的索引

Kha*_*han 7 python find cpu-word

word = 'laugh'    
string = 'This is laughing laugh'
index = string.find ( word )
Run Code Online (Sandbox Code Playgroud)

指数是8,应该是17.我用力环顾四周,但找不到答案.

Dee*_*ace 24

您应该使用正则表达式(带字边界)作为str.find一次出现的返回.然后使用对象的start属性match来获取起始索引.

import re

string = 'This is laughing laugh'

a = re.search(r'\b(laugh)\b', string)
print(a.start())
>> 17
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关其工作原理的更多信息.

  • @Khan 就像使用任何 Python 字符串一样。你可以连接或使用`.format`,即`word = 'laugh'; re.search(r'\b({})\b'.format(word), string)` (3认同)

Dan*_*Lee 6

尝试这个:

word = 'laugh'    
string = 'This is laughing laugh'.split(" ")
index = string.index(word)
Run Code Online (Sandbox Code Playgroud)

这会生成一个包含所有单词的列表,然后搜索相关单词。然后我想你可以添加列表中小于索引的元素的所有长度,并以这种方式找到你的索引

position = 0
for i,word in enumerate(string):
    position += (1 + len(word))
    if i>=index:
        break

print position  
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。


Xtr*_*osh 1

代码中的字符串不以空格分隔。如果要查找空格,则必须在要搜索的单词中包含空格。您可能会发现将字符串拆分为单词然后进行迭代实际上会更有效,例如:

str = "This is a laughing laugh"
strList = str.split(" ")
for sWord in strList:
    if sWord == "laugh":
        DoStuff()
Run Code Online (Sandbox Code Playgroud)

在迭代时,您可以将当前单词的长度添加到索引中,当找到该单词时,从循环中中断。不要忘记考虑空间!