蟒蛇 |從給定的字符串中提取單詞

| | | | | | | | | | | | | | | | | | |

方法一:使用split()
使用split函數,我們可以將一個字符串拆分成一個單詞列表,這個是最常用的如果有人想完成此特定任務,建議使用方法。但缺點是在字符串包含標點符號的情況下不起作用。


# Python3 demo code < br> # 從字符串中提取單詞
# 使用 split()


# 初始化字符串

test_string = "Geeksforgeeks 是最好的計算機科學門戶"


# 打印原始行

print ( "原字符串為:" + test_string)


# 使用 split()
# 從字符串中提取單詞

r es = test_string.split()


# 打印結果

print ( "單詞列表是:" + str (res) )

退出:

原文為:Geeksforgeeks is best Computer Science Portal
The單詞列表是:[`Geeksforgeeks`,`is`, `best`, `Computer`, `Science`, `Portal`]

方法 #2:使用 regex (findall ())
在包含所有特殊字符和標點符號的情況下,如上所述,tr 使用拆分在字符串中搜索單詞的傳統方法可能會失敗並且因此需要正則表達式來完成這項任務。 findall 函數過濾字符串並提取單詞後返回一個列表,忽略標點符號。


# Python3 demo code
# 從字符串中提取單詞
# 使用正則表達式 (findall ())

import re


# 初始化字符串

test_string = "Geeksforgeeks ,最好@#計算機科學門戶網站。!!!”


# 打印原行

print ( "原字符串為:" + test_string)


# 使用正則表達式 (findall())
# 從字符串中提取單詞

res = re.findall (r `w +` , test_string)


# 打印結果

print ( "單詞列表是:" + str (res))

輸出:

原字符串是:Geeksforgeeks,最好是@#計算機科學門戶。 !!!
單詞列表是:[`Geeksforgeeks`,`is`,`best`,`Computer`,`Science`,`Portal`]

方法#3:使用regex() + string.punctuation
該方法也使用了正則表達式,但是get all punctuation string函數用於忽略所有標點符號,獲取過濾後的結果字符串。 p>

# Python3 演示代碼
# 從字符串中提取單詞 < br> # 使用正則表達式 () + string.punctuation

import re

import string


# 初始化字符串

test_string = " Geeksforgeeks, 最好@#Computer Science Portal. !!! "


# 打印原始字符串

print ( " 原始字符串為:" + test_string)


# 使用正則表達式 () + string.punctuation
# 從字符串中提取單詞

res = re.sub ( `[` + string.punctuation + `] ` ,` `, test_string ) .split ()


# 打印結果

print ( "單詞列表是:" + str ( res))

退出:

原文是:Geeksforgeeks,最好是@#計算機科學門戶。 !!!
單詞列表是:[`Geeksforgeeks`, `is`, `best`, `Computer`, `Science`, `Portal`]