示例1 :
start = 42
end = 48
string = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]."Output = [9,9]使用开始索引和结束索引,如何返回完整单词的索引?(在开始位置和结尾位置,这是字符串的第九个单词)
示例2 :
start = 42
end = 52
string = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]."Output = [9,10]在第二种情况下,选择了多个单词,因此我们需要返回第一个单词的索引(Noggin)和最后一个单词的索引(can)。
示例3(输出总是2个数字) :
start = 42
end = 61
string = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]."Output = [9,11]Output = first_word_index,last_word_index
示例4(如果在末尾选择了一个空格,我们不关心) :
start = 42
end = 49
string = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]."Output = [9,9]示例5(如果没有完全选择单词) :
start = 42
end = 51
string = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]."Output = [9,10]如果一个词没有被完全选中,我们的表现就像它被完全选中了一样。

发布于 2021-05-25 13:01:09
以下功能应适用于任何示例:
def words(start,end,string):
c=1
l=[]
for i in range(end):
if string[i]==' ':
c=c+1
if i==start:
l.append(c)
if string[i]!=' ':
l.append(c)
else:
l.append(c-1)
return l发布于 2021-05-25 13:11:08
可以使用正则表达式,查找所有单词,这将返回索引的一个元组:
from typing import Tuple
def word_index(string : str, start : int, end : int) -> Tuple[int, int]:
import re
word_re = re.compile(r'\w+')
start_index = len(word_re.findall(string[:start+1]))
end_index = len(word_re.findall(string[:end]))
return start_index, end_index
word_index(42, 48) # (9, 9)
word_index(42, 52) # (9, 10)
word_index(42, 61) # (9, 11)
word_index(42, 49) # (9, 9)
word_index(42, 51) # (9, 10)https://stackoverflow.com/questions/67688125
复制相似问题