Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Số xuất hiện nhiều nhất trong chuỗi dùng Regex trong Python

Trong hướng dẫn này, chúng ta viết regex tìm số xuất hiện nhiều nhất trong chuỗi. Kiểm tra bằng Python.

Các bước:

  • Import module re và collections.
  • Khởi tạo chuỗi chứa số.
  • Tìm tất cả số bằng regex, lưu vào mảng.
  • Dùng Counter từ collections tìm số xuất hiện nhiều nhất.

Ví dụ

import re
import collections

string = '1222tutorials321232point3442'
regex = r'[0-9]'
numbers = re.findall(regex, string)
counter = collections.Counter(numbers)

high_frequency = 0
highest_frequency_number = None
for key in list(counter.keys()):
    if counter[key] > high_frequency:
        high_frequency = counter[key]
        highest_frequency_number = key
print(highest_frequency_number)

Kết quả

2

Kết luận

Dùng regex + Counter tìm số xuất hiện nhiều nhất. Hãy bình luận nếu có thắc mắc.