我有一个数据集,其中包含数百万个文本文件,其中数字保存为字符串,并使用各种区域设置来格式化数字。我想做的是猜测哪个符号是小数点分隔符,哪个是千位分隔符。
这不应该太难,但似乎还没有提出这个问题,为了后代应该在这里提出和回答这个问题。
我所知道的是,总是有一个小数点分隔符,它总是字符串中最后一个非 [0-9] 符号。
正如您在下面看到的,一个简单的 numStr.replace(',', '.')
修复了小数分隔符的变化将与可能的千位分隔符冲突。
如果您知道语言环境,我已经看到了这样做的方法,但在这种情况下我不知道语言环境。
数据集:
1.0000 //1.0
1,0000 //1.0
10,000.0000 //10000.0
10.000,0000 //10000.0
1,000,000.0000 // 1000000.0
1.000.000,0000 // 1000000.0
//also possible
1 000 000.0000 //1000000.0 with spaces as thousand separators
最佳答案
一种方法:
import re
with open('numbers') as fhandle:
for line in fhandle:
line = line.strip()
separators = re.sub('[0-9]', '', line)
for sep in separators[:-1]:
line = line.replace(sep, '')
if separators:
line = line.replace(separators[-1], '.')
print(line)
在您的示例输入(删除注释)中,输出为:
1.0000
1.0000
10000.0000
10000.0000
1000000.0000
1000000.0000
1000000.0000
更新:处理 Unicode
正如 NeoZenith 在评论中指出的那样,对于现代 unicode 字体,古老的正则表达式 [0-9]
并不可靠。请改用以下内容:
import re
with open('numbers') as fhandle:
for line in fhandle:
line = line.strip()
separators = re.sub(r'\d', '', line, flags=re.U)
for sep in separators[:-1]:
line = line.replace(sep, '')
if separators:
line = line.replace(separators[-1], '.')
print(line)
如果没有 re.U
标志,\d
等同于 [0-9]
。 With that flag , \d
匹配 Unicode 字符属性数据库中归类为十进制数字的任何内容。或者,为了处理不寻常的数字字符,可能需要考虑使用 unicode.translate
.
关于Python:检测数字分隔符并解析为没有语言环境的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941117/