【问题标题】:Conversion types in PythonPython 中的转换类型
【发布时间】:2018-08-18 18:10:07
【问题描述】:

我有以下代码

text_file = open("up2017.txt", "r")
amount=[]
for line in text_file:

    fields =  line.strip().split(" ")
    amount.append(fields[-1])

list(map(float,amount))

我收到以下错误

ValueError: 无法将字符串转换为浮点数:'50.000,00'

文本文件看起来像

13.10    Ovf           12.10            50.000,00                50.000,00
30.10    Bgs                              30.10            12.000,00                62.000,00
30.11    Bgs                              30.11            12.000,00                74.000,00
15.12    Bgs                              15.12            53.528,36               127.528,36
30.12    Bgs                             30.12            12.000,00               139.528,36

【问题讨论】:

    标签: python string python-3.x dictionary


    【解决方案1】:

    正确的做法是使用适当的locale

    例如,在西班牙语国家,使用. 作为千位分隔符和, 作为小数分隔符是很常见的。

    import locale
    locale.setlocale(locale.LC_NUMERIC, 'es')
    value = locale.atof('50.032,56') # yields float(50032.56)
    

    在您的情况下,您可以执行以下操作:

    import locale
    locale.setlocale(locale.LC_NUMERIC, 'es')
    
    # ...
    
    values = map(locale.atof, amount)
    

    【讨论】:

      【解决方案2】:

      使用str.replace 方法:

      amount.append(fields[-1].replace('.', '').replace(',', '.'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-23
        • 2019-04-08
        • 1970-01-01
        • 1970-01-01
        • 2016-07-27
        • 1970-01-01
        • 2018-03-07
        相关资源
        最近更新 更多