Python中通过start_index和end_index查找句子单词位置的实现方法
实现思路
- 先预处理字符串,提取所有单词的起止下标和对应序号(从1开始计数),单词按空格分割,连续非空格字符视为一个单词
- 按规则处理输入的end下标:如果end对应位置是空格,向左查找第一个非空格字符的位置作为实际生效的end边界,忽略末尾空格
- 遍历单词列表匹配覆盖范围:
- 首个被覆盖的单词:第一个单词结束下标 >= 输入start的单词(只要部分重叠就算覆盖,符合规则4)
- 最后一个被覆盖的单词:最后一个单词起始下标 <= 处理后end的单词
- 返回[首个单词序号, 最后一个单词序号]即可
实现代码
def get_covered_word_range(start: int, end: int, string: str) -> list[int]: # 预处理得到所有单词的起止位置和序号 words = [] word_start = None str_len = len(string) for idx, char in enumerate(string): if char != ' ': if word_start is None: word_start = idx else: if word_start is not None: words.append((word_start, idx - 1, len(words) + 1)) word_start = None # 补充最后一个单词的记录 if word_start is not None: words.append((word_start, str_len - 1, len(words) + 1)) # 处理end边界,忽略末尾空格 actual_end = min(end, str_len - 1) while actual_end >= 0 and string[actual_end] == ' ': actual_end -= 1 # 极端场景处理:选中范围全是空格可自行调整返回规则,示例无此场景 if actual_end < 0 or start > actual_end: return [] # 查找第一个被覆盖的单词 first = None for w in words: w_start, w_end, w_idx = w if w_end >= start: first = w_idx break # 查找最后一个被覆盖的单词 last = None for w in reversed(words): w_start, w_end, w_idx = w if w_start <= actual_end: last = w_idx break return [first, last]
示例测试
test_str = "This is in line with others, showing that Noggin can function as a BMP-6 antagonist [21,22]." print(get_covered_word_range(42, 48, test_str)) # 输出 [9,9] print(get_covered_word_range(42, 52, test_str)) # 输出 [9,10] print(get_covered_word_range(42, 61, test_str)) # 输出 [9,11] print(get_covered_word_range(42, 49, test_str)) # 输出 [9,9] print(get_covered_word_range(42, 51, test_str)) # 输出 [9,10]
所有测试用例输出与示例要求完全一致。
内容的提问来源于stack exchange,提问作者R M
相关产品推荐
相关产品推荐

