如何从字符串中的匹配单词中获取左右大多数索引

时间:2016-05-05 16:30:40

标签: python

使用:

phrase = "this is string example....wow!!!"
word = "example"

我想知道word内匹配phrase的最左侧和最右侧索引是什么。如何用最少的编码做到这一点?

输出应该是两个整数值。首先是word的第一个字母的有序编号:“e”。第二个整数值是word的最后一个字母的有序数字:相同的字符“e”(在“示例中”,第一个和最后一个字母是相同的)。我们需要找到阶段“这是字符串示例....哇!!!” “例子”这个词是。

3 个答案:

答案 0 :(得分:2)

我假设您只想在def check_keys(): allKeys = event.getKeys(keyList = ('g','h','escape')) for thisKey in allKeys: if thisKey == 'escape': dataFile.close() window.close() core.quit() elif thisKey == 'g': keyTime=core.getTime() return 1 elif thisKey == 'h': keyTime=core.getTime() return 0 return 2 thisResp = 2 running = 1 while running == 1: for frame in range(frames): fix.draw() upper_target.draw() z= window.flip() thisResp = check_keys() if thisResp == 1: running = 2 break print running 中找到word的第一个匹配项。如果是这种情况,只需使用phrase来获取第一个字符的位置。然后,向其添加str.index以获取最后一个字符的位置。

len(word) - 1

如果您需要查找所有次出现start = phrase.index(word) # 15 end = start + len(word) - 1 # 21 的索引,则使用word模块会更容易:

re

打印

import re

for m in re.finditer(word, "example example"):
    print(m.start(), m.end() - 1)

答案 1 :(得分:2)

这是一种不使用re包的方法。它还将返回所有出现的word

的开始/结束索引
phrase = "this is string example....wow!!!"
word = "example"

word_len = len(word) # word length is 7
phrase_len = len(phrase) # phrase length is 32

#We loop through the phrase using a "window" size equal to the word length
#If we find a match, we return the first and last index of the "current" window
for i in range(phrase_len - word_len+1):
    current = phrase[i:i+word_len]
    if current == word:
        print i,i+word_len-1

#prints 15, 21

答案 2 :(得分:1)

这个怎么样:

import re

phrase = "this example is  example string example....wow example!!!"
word = "example"

start, end = min([(m.start(0), m.end(0)) for m in re.finditer(word, phrase)])
print start, end - 1  # 5 11
print phrase[start:end]  # example