使用 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

結論

如果您對本教程有任何疑問,請在評論中說明。

更新於:2020 年 7 月 11 日

172 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告