在python中使用Regex在字符串中出现次数最多的数字
在本教程中,我们将编写一个正则表达式来查找字符串中出现次数最多的数字。我们将在Python中检查正则表达式。
请按照以下步骤编写程序。
导入re和collections模块。
用数字初始化字符串。
4使用正则表达式查找所有数字并将其存储在数组中。
使用“来自收藏夹的计数器”模块查找出现次数最多的数字。
示例
# 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
结论
如果您对本教程有任何疑问,请在评论部分中提及。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志