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

WBOY
WBOY 转载
2023-08-28 09:17:06 715浏览

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)

# 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 步 - 将给定的Str 作为测试字符串,然后使用 split 函数将其分成单词,并将其称为 listofwords。

第3步 - 现在使用align_tokens和listofwords作为标记以及给定的Str。

步骤 4 - 它将返回单词索引列表,但包含空格。最后一个单词索引值减一即可得到不包含空格的单词索引列表。

第 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 的所需模块。使用此模块并指定单词列表中的标记,可以找到所有单词的索引。

以上就是Python程序:找到字符串中所有单词的起始和结束索引的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除