Python程序:找到字符串中所有单词的起始和结束索引
有时,我们需要一个单词的起始索引以及该单词的最后一个索引。句子由用空格分隔的单词组成。在这篇 Python 文章中,使用两个不同的示例,给出了查找句子或给定字符串中所有单词的开头和结尾索引的两种不同方法。在第一个示例中,遵循对字符串的所有字符进行简单迭代的过程,同时查找标记单词开头的空格。在示例 2 中,自然语言工具包用于查找字符串中所有单词的开始和结束索引。
示例 1 - 通过迭代字符串查找字符串中所有单词的开始和结束索引。
算法
第 1 步 - 首先获取一个字符串并将其命名为给定Str。
第 2 步 - 创建一个名为 StartandEndIndex 的函数,该函数将获取此给定的 Str 并迭代它,检查空格并返回具有所有单词的开始和结束索引的元组列表。
第 3 步 - 使用 split 方法创建单词列表。
第 4 步 - 使用上面两个列表中的值并创建一个字典。
第 5 步 - 运行程序,然后检查结果。
Python 文件包含此内容
#function for given word indices def StartandEndIndex(givenStr): indexList = [] startNum = 0 lengthOfSentence=len(givenStr) #iterate though the given string for indexitem in range(0,lengthOfSentence): #check if there is a separate word if givenStr[indexitem] == " ": indexList.append((startNum, indexitem - 1)) indexitem += 1 startNum = indexitem if startNum != len(givenStr): indexList.append((startNum, len(givenStr) - 1)) return indexList givenStr = 'Keep your face always toward the sunshine and shadows will fall behind you' #call the function StartandEndIndex(givenStr) #and get the list having starting and ending indices of all words indexListt = StartandEndIndex(givenStr) 1. make a list of words separately listofwords= givenStr.split() print("nThe given String or Sentence is ") print(givenStr) print("nThe list of words is ") print(listofwords) #make a dictionary using words and their indices resDict = {listofwords[indx]: indexListt[indx] for indx in range(len(listofwords))} print("nWords and their indices : " + str(resDict)) 登录后复制