【问题标题】:Parse a string to floats with different separators将字符串解析为具有不同分隔符的浮点数
【发布时间】:2012-02-10 11:52:29
【问题描述】:

我有许多字符串表示数字,这些数字使用逗号或点来分隔千位并具有不同的浮动分隔符。例如:

“22 000,76”、“22.000,76”、“22,000.76”、“1022000,76”、“-1,022,000.76”、“1022000”、“22 000,76美元”、“22 000,76美元”

如何在 Python 中将这些转换为浮点数?

在 PHP 中我使用这样的函数:http://docs.php.net/manual/sr/function.floatval.php#84793

【问题讨论】:

  • 你能告诉我们你需要的输出吗?我对你的例子有点困惑。
  • 示例输出:22000.76、22000.76、22000.76、1022000.76、-1022000.76、1022000、22000.76、22000.76 - 浮点数
  • @Bondarenko:“100,000”呢?
  • @BondarenkoMikhail:还有什么?我认为这可能意味着 100000 或 100.0
  • 完整示例:“22 000,76”、“22.000,76”、“22,000.76”、“22 000”、“22,000”、“22.000”、“22000.76”、“22000,76” ,"1.022.000,76","1,022,000.76","1,000,000","1.000.000","1022000.76","1022000,76","1022000","0.76","0,76","0.00" ,"0,00","1.00","1,00","-22 000,76","-22.000,76","-22,000.76","-22 000","-22,000","- 22.000","-22000.76","-22000,76","-1.022.000,76","-1,022,000.76","-1,000,000","-1.000.000","-1022000.76","-1022000, 76","-1022000","-0.76","-0,76","-0.00","-0,00","-1.00","-1,00"

标签: python numbers floating-point


【解决方案1】:
import re
import locale

# Remove anything not a digit, comma or period
no_cruft = re.sub(r'[^\d,.-]', '', st)

# Split the result into parts consisting purely of digits
parts = re.split(r'[,.]', no_cruft)

# ...and sew them back together
if len(parts) == 1:
    # No delimeters found
    float_str = parts[0]
elif len(parts[-1]) != 2:
    # >= 1 delimeters found. If the length of last part is not equal to 2, assume it is not a decimal part
    float_str = ''.join(parts)
else:
    float_str = '%s%s%s' % (''.join(parts[0:-1]),
                            locale.localeconv()['decimal_point'],
                            parts[-1])

# Convert to float
my_float = float(float_str)

【讨论】:

  • 如果@Niklas B 建议的“100,000”应该是 100000,请不要使用我的答案。
  • 使用locale.localeconv()['decimal_point'] 来确保在当前语言环境中小数点不是'.'float 不会失败可能会很有趣。
  • 假设来自@BondarenkoMikhail 的最后一条评论(已删除(?))所有小数部分(如果存在)应该由 2 位数字组成。编辑了我的答案以反映这一事实。
  • 我不认为使用locale 是合适的,因为输入显然来自多种语言环境——尽管它可以说是猜测或提供默认解释......跨度>
  • 内置 float() 似乎不使用语言环境来解析字符串,因此为小数点分隔符设置 locale.localeconv()['decimal_point'] 是不正确的。最好将其设置为固定的“。”
【解决方案2】:

假设您最多有 2 个十进制数字:

sign_trans = str.maketrans({'$': '', ' ':''})
dot_trans = str.maketrans({'.': '', ',': ''})

def convert(num, sign_trans=sign_trans, dot_trans=dot_trans):
    num = num.translate(sign_trans)
    num = num[:-3].translate(dot_trans) + num[-3:]
    return float(num.replace(',', '.'))

我在你的例子中测试它:

>>> for n in nums:
...     print(convert(n))
...
22000.76
22000.76
22000.76
1022000.76
-1022000.76
1022000.0
22000.76
22000.76

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2019-12-30
    • 2012-11-25
    • 2016-04-17
    • 2019-06-03
    • 2012-10-23
    • 2015-09-02
    • 2020-09-02
    相关资源
    最近更新 更多