Python程序查找字符串中所有单词的起始和结束索引


有时,我们需要单词的起始索引以及该单词的最后一个索引。一个句子由用空格分隔的单词组成。在这篇Python文章中,通过两个不同的示例,给出了两种查找句子或给定字符串中所有单词的起始和结束索引的不同方法。在第一个示例中,在查找空格以标记单词的开头时,遵循了对字符串所有字符进行简单迭代的过程。在示例2中,使用自然语言工具包来查找字符串中所有单词的起始和结束索引。

示例1 - 通过迭代字符串查找字符串中所有单词的起始和结束索引。

算法

步骤1 − 首先取一个字符串并将其称为givenStr。

步骤2 − 创建一个名为StartandEndIndex的函数,该函数将接收此givenStr并对其进行迭代,检查空格并返回一个包含所有单词的起始和结束索引的元组列表。

步骤3 − 使用split方法创建listofwords。

步骤4 − 使用上面两个列表中的值创建一个字典。

步骤5 − 运行程序,然后检查结果。

Python文件包含这些内容

Open Compiler
#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) # 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))

查看结果 - 示例1

要查看结果,请在cmd窗口中运行Python文件。

The given String or Sentence is
Keep your face always toward the sunshine and shadows will fall behind you

The list of words is
['Keep', 'your', 'face', 'always', 'toward', 'the', 'sunshine', 'and', 'shadows', 'will', 'fall', 'behind', 'you']

Words and their indices : {'Keep': (0, 3), 'your': (5, 8), 'face': (10, 13), 'always': (15, 20), 'toward': (22, 27), 'the': (29, 31), 'sunshine': (33, 40), 'and': (42, 44), 'shadows': (46, 52), 'will': (54, 57), 'fall': (59, 62), 'behind': (64, 69), 'you': (71, 73)}

图1:在命令窗口中显示结果。

示例2:使用nltk(自然语言工具包)查找字符串中所有单词的起始和结束索引。

算法

步骤1 − 首先使用pip命令安装nltk。现在从中导入align_tokens。

步骤2 − 将givenStr作为测试字符串,然后使用split函数将其分成单词,并将其称为listofwords。

步骤3 − 现在使用align_tokens,其中listofwords作为标记和givenStr。

步骤4 − 它将返回一个单词索引列表,但将包含空格。从最后一个单词索引值中减去1以获取不包含空格的单词索引列表。

步骤5 − 使用上面两个列表中的值创建一个字典。

步骤6 − 运行程序,然后检查结果。

Python文件包含这些内容

#Use pip install nltk to install this library #import align tokens from nltk.tokenize.util import align_tokens #specify a string for testing givenStr = 'Keep your face always toward the sunshine and shadows will fall behind you' #make a list of words listofwords= givenStr.split() print("\nThe given String or Sentence is ") print(givenStr) print("\nThe list of words is ") print(listofwords) #this will include blank spaces with words while giving indices indices_includingspace= align_tokens(listofwords, givenStr) indices_withoutspace=[] #reduce the last index number of the word indices for item in indices_includingspace: #convert tuple to list lst = list(item) lst[1]=lst[1] - 1 #convert list to tuple again tup = tuple(lst) indices_withoutspace.append(tup) print(indices_withoutspace) #make the dictionary of all words in a string with their indices resDict = {listofwords[indx]: indices_withoutspace[indx] for indx in range(len(listofwords))} print("\nWords and their indices : " + str(resDict))

查看结果 - 示例2

打开cmd窗口并运行python文件以查看结果。

The given String or Sentence is
Keep your face always toward the sunshine and shadows will fall behind you

The list of words is
['Keep', 'your', 'face', 'always', 'toward', 'the', 'sunshine', 'and', 'shadows', 'will', 'fall', 'behind', 'you']
[(0, 3), (5, 8), (10, 13), (15, 20), (22, 27), (29, 31), (33, 40), (42, 44), (46, 52), (54, 57), (59, 62), (64, 69), (71, 73)]

Words and their indices : {'Keep': (0, 3), 'your': (5, 8), 'face': (10, 13), 'always': (15, 20), 'toward': (22, 27), 'the': (29, 31), 'sunshine': (33, 40), 'and': (42, 44), 'shadows': (46, 52), 'will': (54, 57), 'fall': (59, 62), 'behind': (64, 69), 'you': (71, 73)}

图2:显示单词及其索引。

在这篇Python文章中,通过两个不同的示例,给出了查找字符串中所有单词的起始和结束索引的方法。在示例1中,给出了通过迭代字符串的所有字符来执行此操作的方法。在这里,选择空格来标记新单词的开始。在示例2中,使用了一个库nltk或自然语言工具包。首先,使用pip安装它。然后导入名为align_tokens的必需模块。使用此模块并指定单词列表中的标记,可以找到所有单词的索引。

更新于: 2023年7月10日

246 次浏览

开启你的职业生涯

完成课程获得认证

立即开始
广告