代码之家  ›  专栏  ›  技术社区  ›  aabujamra

选择字符串中最大的货币值

  •  0
  • aabujamra  · 技术社区  · 6 年前

    “达利西塔”§o:r$ (quarenta e trs mil,quatrocentos e setenta reais)\n\n3 dos recursos或§amento so r$ "

    请注意,我的字符串中可能有几个货币值。 我只想分开最大的,回报应该是“43.470,00”或43470.00或43470。

    我怎么能那样做?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Yam Mesicka    6 年前
    # Create regular expression pattern for currencies
    currency_pattern = re.compile(r"r\$ ([1-9][0-9.]*(?:,[0-9][0-9.]*)?)")
    
    # Find the currencies in the string
    currencies = currency_pattern.findall(" da licitação: r$ 43.470,00 (quarenta e três mil, quatrocentos e setenta reais)\n\n3 dos recursos orçamento são r$ 24.123,88")
    
    # Reformat strings and cast to float
    normalized_currencies = (float(currency.replace('.', '').replace(',', '.')) for currency in currencies)
    
    # Now we can easily find the maximum value using the `max` function
    max_currency = max(normalized_currencies)
    print(max_currency)
    

    43470.0个

        2
  •  2
  •   Andrej Kesely    6 年前

    您可以使用regex执行此任务:

    import re
    
    s = ''' da licitação: r$ 43.470,00 (quarenta e três mil, quatrocentos e setenta reais)\n\n3 dos recursos orçamento são r$ 24.123,88'''
    m = max(re.findall(r'\d+\.?\d*,?\d*', s), key=lambda v: float(v.replace('.', '').replace(',', '.')), default=None)
    print(m)
    

    43.470,00
    
        3
  •  1
  •   Ivan    6 年前

    这样就可以了(返回一个整数!): 我从 here

    # Python3 program to extract all the numbers from a string 
    import re 
    
    # Function to extract all the numbers from the given string 
    def getNumbers(str): 
        array = re.findall(r'[0-9]+', str) 
        return array 
    
    # Driver code 
    string = "adbv34.5hj43hvb42"
    line = ''
    line = re.sub('[!@#$]', '', string)
    
    array = getNumbers(line)
    
    arra_num = []
    
    for nums in array:
        arra_num.append(int(nums))
    
    print(max(arra_num))