使用 Python 中的正則表示式在字串中找出出現次數最多的數字
本教程中,我們將編寫一個正則表示式,找出字串中出現次數最多的數字。我們將在 Python 中驗證正則表示式。
按照以下步驟編寫程式。
- 匯入 re 和 collections 模組。
- 使用數字初始化字串。
- 使用正則表示式查詢所有數字,並將它們儲存在陣列中。
- 使用 collections 模組中的 Counter 找出出現次數最多的數字。
示例
# importing the modules import re import collections # initializing the string string = '1222tutorials321232point3442' # regex to find all the numbers regex = r'[0-9]' # getting all the numbers from the string numbers = re.findall(regex, string) # counter object counter = collections.Counter(numbers) # finding the most occurring number high_frequency = 0 highest_frequency_number = None for key in list(counter.keys()): if counter[key] > high_frequency: highest_frequency_number = counter[key] # printing the number print(highest_frequency_number)
輸出
如果您執行以上程式碼,將獲得以下結果。
2
結論
如果您對本教程有任何疑問,請在評論中說明。
廣告