带有本地输入的 Python atof [英] Python atof with local input

查看:42
本文介绍了带有本地输入的 Python atof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个(德语)表达式,它读取 10.401,40(在 Mio EUR),我想将其转换为真正的浮点数(在这种情况下约为 100 亿)蟒蛇.
这是我迄今为止所拥有的:

Say, I have a (German) expression which reads 10.401,40 (in Mio EUR), I'd like to convert this to a real float (in this case around 10 billions) in Python.
This is what I have thus far:

import re, locale
from locale import *
locale.setlocale(locale.LC_ALL, 'de_DE') 

string = "10.401,40 (in Mio EUR)"
m = re.search(r'([\d.,]+)', string)
if m is not None:
    number = atof(m.group(1)) * 10**6

但是,它会引发 ValueError(ValueError:float() 的无效文字:10.401.40).
为什么?.setlocale() 指令不是应该处理这个吗?有没有我(还!)不知道的 Pythonic 方式?

However, it raises a ValueError (ValueError: invalid literal for float(): 10.401.40).
Why? Isn't the .setlocale() directive supposed to be handling exactly this? Is there a pythonic way that I am (yet!) unaware of?

推荐答案

我遇到了相同的 ValueError.正如这个类似的问题所解释的,您需要在您的系统.按照上述操作,我输入 sudo dpkg-reconfigure locales 并选择 de-DE.UTF-8.我不得不修改语言环境设置行以匹配 locale.setlocale(locale.LC_ALL, 'de_DE.utf8') 并让您的代码段运行.祝你好运!

I got the same ValueError. As this similar question explains, you need to have the German locale installed in your system. Following the above, I typed in sudo dpkg-reconfigure locales and selected de-DE.UTF-8. I had to modify the locale setting line to match with locale.setlocale(locale.LC_ALL, 'de_DE.utf8') and got your snippet to run. Good luck!

这篇关于带有本地输入的 Python atof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆