使用Python查詢同時包含字母和數字的單詞
Python 是一種高階程式語言,具有各種工具和內建函式來分析文字資料。本問題陳述是一個常見任務,它使用一些內建函式——filter()、isdigit()、isalpha()、findall()、split()和append()——來使用 Python 查詢同時包含字母和數字的單詞。
讓我們看看如何獲取程式的輸入以獲得結果
輸入
my_text = "WELCOME TO CLUB100"
輸出
CLUB100
語法
以下語法在示例中使用:
filter()
當根據特定條件過濾專案時,應用 filter() 方法。簡單來說,它允許使用者迭代提取的元素以滿足條件。
isdigit()
isdigit() 是 Python 中的內建方法,如果找到的字元是數字則返回 true,否則返回 false。
isalpha()
如果所有字元都是 a-z 之間的字母,則此內建函式返回 true。
re.findall()
findall() 方法遵循名為 re 的模組以返回字串列表。re 代表正則表示式,它嘗試從輸入文字中匹配模式。
split()
split() 是 Python 中的內建方法,它將單詞列表分解成字串。
append()
append() 函式用於將文字元素新增到列表的末尾。
使用正則表示式
程式在相應的變數中使用正則表示式符號,並使用內建函式 findall() 查詢字母。
示例
在下面的示例中,首先定義名為 find_alphabet_num 的函式,該函式接受文字字串作為引數。然後,該函式使用正則表示式查詢包含字母和數字的文字的模式匹配。接下來,它將使用遵循 re 模組的 findall() 方法查詢模式文字的所有出現。
import re def find_alphabets_num(text): pattern = r'\b(?=\w*\d)(?=\w*[a-zA-Z])\w+\b' words = re.findall(pattern, text) return words # create the string my_text = "This is RX100" # function call result = find_alphabets_num(my_text) print(result)
輸出
['RX100']
使用列表推導和 split 方法
程式使用 split() 分隔各個單詞,並使用列表推導包含各種內建函式——isdigit()、isalpha() 和 any()——來迭代迴圈。
示例
在下面的示例中,函式 find_alphabet_num 接受一個輸入字串。然後,split 函式將輸入文字分成單詞,只包含包含字母和數字的單詞。接下來,使用 return 函式將單詞作為列表返回。然後建立一個字串儲存在變數 **my_text** 中。函式呼叫將使用變數 result 傳遞引數,即 **my_text**。最後,我們藉助變數 **result** 列印輸出。
def find_alphabet_num(text): words = text.split() filtered_words = [word for word in words if any(c.isdigit() for c in word) and any(c.isalpha() for c in word)] return filtered_words # Create the string my_text = "Microsoft365, MS Word, MS Excel" # function call result = find_alphabet_num(my_text) print(result)
輸出
['Microsoft365,']
使用迴圈和字串方法
程式使用 for 迴圈透過使用遞迴函式、split()、any()、isalpha() 和條件語句來迭代輸入字串。
示例
在下面的示例中,首先定義名為 **find_words_alphabet** 的函式,該函式接受引數名稱 text(接收輸入字串值)。然後,split() 方法分隔單詞並檢查單詞是否包含字串作為輸入。接下來,使用三個簡單的步驟——建立字串、函式呼叫和 print 函式——來獲得所需的結果。
def find_words_alphabets_num(text): words = text.split() filtered_words = [] for word in words: if any(c.isdigit() for c in word) and any(c.isalpha() for c in word): filtered_words.append(word) return filtered_words # Create the string my_text = "Microsoft365, MS Word, MS Excel" # function call result = find_words_alphabets_num(my_text) print(result)
輸出
['Microsoft365,']
使用 Lambda 函式和 filter()
程式使用 filter() 刪除字串中包含數字的字元。lambda 函式使用 for 迴圈和內建函式 [any() 和 isdigit()] 計算字母和數字的結果。
示例
在下面的示例中,函式 **find_alphabet_number** 接受引數 **text**,透過函式呼叫接收字串的值。然後,它將使用名為 **split()** 的方法使用內建方法 **filter()** 和 **lambda** 分隔所有包含數字和字母的單詞,並將它們儲存在變數 **words** 中。接下來,它使用 return 函式返回列表。接下來在變數 my_text 中建立輸入字串。然後在變數 result 中使用函式呼叫,並在 print 函式中使用相同的變數來獲得結果。
def find_alphabet_number(text): words = text.split() filtered_words = filter(lambda word: any(c.isdigit() for c in word) and any(c.isalpha() for c in word), words) return list(filtered_words) # Create the string my_text = "My World123" result = find_alphabet_number(my_text) print(result)
輸出
['World123']
結論
我們討論了查詢同時包含字母和數字的單詞的各種方法。例如,正則表示式有助於設定包含字母及其數字的輸入文字的模式匹配,而其他內建函式也可以解決同樣的問題。