1

我目前正在使用查找功能,发现一个小问题。

这里会着火

如果我有一个带有单词“here”和“theres”的句子,并且我使用 find() 来查找“here”的索引,我会得到“theres”

我认为 find() 会像 thatword 中的 thisword 一样:

因为它会找到单词,而不是字符串中的子字符串。

是否有其他功能可以类似地工作?我正在使用 find() 非常想知道替代方案,然后再用 string.split() 阻塞代码然后迭代,直到找到与旁边的索引计数器完全匹配为止。

MainLine = str('theres gonna be a fire here')
WordtoFind = str('here')
#String_Len =  MainLine.find(WordtoFind)
split_line = MainLine.split()

indexCounter = 0
for i in range (0,len(split_line)):
     indexCounter += (len(split_line[i]) + 1)
     if WordtoFind in split_line[i]:
          #String_Len =  MainLine.find(split_line[i])
          String_Len = indexCounter 
          break
4

1 回答 1

2

最好的方法是正则表达式。要查找“单词”,只需确保开头和结尾字符不是字母数字。它不使用拆分,没有暴露的循环,甚至当你遇到像“这里有火”这样的奇怪句子时也能正常工作。find_word 函数可能如下所示

import re
def find_word_start(word, string):
    pattern = "(?<![a-zA-Z0-9])"+word+"(?![a-zA-Z0-9])"
    result = re.search(pattern, string)
    return result.start()
>> find_word_start("here", "There is a fire,here")
>> 16

我制作的正则表达式使用了一种称为lookarounds 的技巧,可确保单词前后的字符不是字母或数字。https://www.regular-expressions.info/lookaround.html。该术语[a-zA-Z0-9]是一个字符集,由集合 az、AZ 和 0-9 中的单个字符组成。查找 python re 模块以了解有关正则表达式的更多信息。

于 2018-11-30T22:34:39.753 回答