📌  相关文章
📜  在Python中使用正则表达式的字符串中出现次数最多的数字

📅  最后修改于: 2022-05-13 01:55:41.969000             🧑  作者: Mango

在Python中使用正则表达式的字符串中出现次数最多的数字

给定一个字符串str ,任务是从字符串中提取所有数字并使用 Regex Python找出其中出现次数最多的元素。

  • 保证没有两个元素具有相同的频率
      例子:
    Input :geek55of55geeks4abc3dr2 
    Output :55
    
    Input :abcd1def2high2bnasvd3vjhd44
    Output :2
    

    方法:使用Python正则表达式库中的re.findall()函数从字符串str中提取所有数字,并使用集合库中的Counter函数,我们可以获得出现次数最多的元素。

    下面是上述方法的Python实现

    # your code goes here# Python program to 
    # find the most occurring element 
    import re 
    from collections import Counter 
      
    def most_occr_element(word):
          
        # re.findall will extract all the elements 
        # from the string and make a list
        arr = re.findall(r'[0-9]+', word)    
          
        # to store maxm frequency
        maxm = 0  
      
        # to store maxm element of most frequency
        max_elem = 0
          
        # counter will store all the number with 
        # their frequencies
        # c = counter((55, 2), (2, 1), (3, 1), (4, 1))    
        c = Counter(arr)
        
        # Store all the keys of counter in a list in
        # which first would we our required element    
        for x in list(c.keys()):
      
            if c[x]>= maxm:
                maxm = c[x]
                max_elem = int(x)
                      
        return max_elem
      
    # Driver program 
    if __name__ == "__main__": 
        word = 'geek55of55gee4ksabc3dr2x'
        print(most_occr_element(word))
    
    输出:
    55