Python 获取字符串匹配中的单词索引

Python 获取字符串匹配中的单词索引,python,regex,string,list,Python,Regex,String,List,我有两条线 str=“这是一个示例句,仅供演示” k=“示例句子”#k可能包含一个或多个单词 我想在str中找到k,但我需要单词索引。 我拆分了str splitted\u str=str.split() 如果我在splitted_str中匹配k,则函数应将示例的索引设为3,将句子的索引设为4 re.search().start()它只提供字符串起始索引 请建议 提前谢谢 试着在你的短语上拆分句子,然后数一数前面的单词 >>> str = "This is an example

我有两条线

str=“这是一个示例句,仅供演示”

k=“示例句子”
#k可能包含一个或多个单词

我想在
str
中找到
k
,但我需要单词索引。 我拆分了
str

splitted\u str=str.split()

如果我在
splitted_str
中匹配
k
,则函数应将
示例的索引设为3,将
句子的索引设为4

re.search().start()
它只提供字符串起始索引

请建议


提前谢谢

试着在你的短语上拆分句子,然后数一数前面的单词

>>> str = "This is an example sentence, it is for demonstration only"
>>>
>>> k = "example sentence"
>>> str.split(k)
['This is an ', ', it is for demonstration only']
>>> str.split(k)[0].split()
['This', 'is', 'an']
>>> len(str.split(k)[0].split())
3
>>>

首先在
str
中搜索
k
,找到字符索引,然后将
str
的部分拆分为该索引。谢谢@Harvey。如果我不知道
k
有一个词或多个词怎么办。任何更新。如果
k
包含多个单词,计算它们并添加到初始单词数中:
3
+(
0
1
,…)谢谢我像这样做了def matcher(text,word):split\u word=word.split()split\u text=text.split(word)If(len(split\u text)>1):start=len(split\u text[0].split())打印(开始)结束=开始+长度(拆分字)-1次打印(结束)
>>> str = "This is an example sentence, it is for demonstration only"
>>>
>>> k = "example sentence"
>>> str.split(k)
['This is an ', ', it is for demonstration only']
>>> str.split(k)[0].split()
['This', 'is', 'an']
>>> len(str.split(k)[0].split())
3
>>>