首頁  >  文章  >  後端開發  >  Python程式:找到字串中所有單字的起始和結束索引

Python程式:找到字串中所有單字的起始和結束索引

WBOY
WBOY轉載
2023-08-28 09:17:061266瀏覽

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.com。如有侵權,請聯絡admin@php.cn刪除