如何在 Python 中將字串轉換為單詞列表?


在本文中,我們將學習如何在 Python 中將字串轉換為單詞列表。

第一種方法是使用內建方法 `split()`。此函式根據我們指定的定界符分割文字。定界符引數傳送到 `split()` 函式,它指示文字應在何處分割。

因此,我們必須將空格作為定界符傳遞給 `split()` 函式。此函式返回一個空格分隔的修改後的列表。

示例 1

在下面的示例中,我們以字串作為輸入,並使用 `split()` 方法將其轉換為單詞列表。

str1 = "Hello Everyone Welcome to Tutoiralspoint"

print("The given string is")
print(str1)

print("Converting them into list of words")
res = str1.split()
print(res)

輸出

給定示例的輸出如下:

The given string is
Hello Everyone Welcome to Tutoiralspoint
Converting them into list of words
['Hello', 'Everyone', 'Welcome', 'to', 'Tutoiralspoint']

示例 2

在下面的示例中,我們使用與上面相同的程式,但我們使用不同的輸入,並將其轉換為單詞列表。

str1 = "Hello-Everyone-Welcome-to-Tutoiralspoint"

print("The given string is")
print(str1)

print("Converting them into list of words")
res = str1.split('-')
print(res)

輸出

上述示例的輸出如下:

The given string is
Hello-Everyone-Welcome-to-Tutoiralspoint
Converting them into list of words
['Hello', 'Everyone', 'Welcome', 'to', 'Tutoiralspoint']

使用 re.split()

在第二種方法中,使用了正則表示式。要使用 re 庫,請匯入它,如果尚未安裝,則安裝它。在載入 re 庫後,我們可以在 `re.split()` 方法中使用正則表示式 '+'。正則表示式和字串作為輸入傳送到 `re.split()` 方法,該方法根據正則表示式指示的字元分割文字。

示例

在下面的示例中,我們以字串作為輸入,並使用正則表示式在空格處分割字串。

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.split('\s+', str1)
print(res)

輸出

上述示例的輸出如下:

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

更新於:2022-12-07

9K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告