Python程序,用于查找字符串中所有单词的开始和结束索引
给定一个字符串,返回每个单词的所有开始索引和结束索引。
例子:
Input : test_str = ‘ Geekforgeeks is Best’
Output : [(1, 12), (16, 17), (19, 22)]
Explanation : “Best” Starts at 19th index, and ends at 22nd index.
Input : test_str = ‘ Geekforgeeks is Best’
Output : [(1, 12), (17, 18), (20, 23)]
Explanation : “Best” Starts at 20th index, and ends at 23rd index.
方法:使用列表理解+正则表达式+ finditer()
在此,我们使用 finditer() 和 regex 提取所有单词,获取初始和结束索引,我们使用 start() 和 end() 并使用列表理解以元组列表的形式进行封装。
Python3
# Python3 code to demonstrate working of
# Word Ranges in String
# Using list comprehension + regex + finditer()
import re
# initializing string
test_str = ' Geekforgeeks is Best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# regex to get words, loop to get each start and end index
res = [(ele.start(), ele.end() - 1) for ele in re.finditer(r'\S+', test_str)]
# printing result
print("Word Ranges are : " + str(res))
输出
The original string is : Geekforgeeks is Best for geeks
Word Ranges are : [(1, 12), (16, 17), (19, 22), (27, 29), (32, 36)]