英語のテキストとスパンを指定して、スパンがテキスト内にあるかどうかを判断し、開始/終了インデックスを返す場合は 1 から数えて、そうでない場合は 0,0 を返します。

# 给定英文text,以及span,判断span是否在text,若在返回start /end index,从1开始计数,如果不在,则返回0,0
import re

text = "This is a tt sample text"
span = "sample text"

def get_index(text, span):
    match = re.search(span, text)
    if match == None:
        index = (0,0)
    else:
        start_index = match.start()
        end_index = match.end()
        words_before_span = text[:start_index].split()
        words = text.split()
        start_word_index = len(words_before_span) + 1
        end_word_index = start_word_index + len(span.split()) - 1
        index =(start_word_index, end_word_index)
    return index
start, end = get_index(text, span)
print(start, end)

Supongo que te gusta

Origin blog.csdn.net/weixin_41862755/article/details/130208417
Recomendado
Clasificación