我有一个文本文件,其中包含一些不同类型的数字:整数、二进制和 float 。我只想匹配 float 并将逗号替换为点。
我的文本文件示例(顺序随意):
1000101 33434,34 1992 [3,41,4,5]
转换后:
1000101 33434.34 1992 [3,41,4,5]
我的代码是:
lines = []
in_file = open("input.txt", "r")
for line in in_file:
line = line.split(" ")
for x in line:
try:
if isinstance(float(x.replace(',', '.')), float):
line[line.index(x)] = float(x.replace(',', '.'))
except:
pass
lines.append(line)
in_file.close()
但这会将所有其他数据转换为 float ,那么解决此问题的最佳方法是什么?
我想使用 regex
但我不知道如何在 python 中使用它。
最佳答案
另一种方法,也使用正则表达式:
import re
with open('input.txt', 'r+') as f:
newf = re.sub(r'(\s+[+-]?[0-9]+),([0-9]+\s+)',r'\1.\2', f.read())
f.seek(0)
f.write(newf)
测试文件:
1000101 33434,34 1992 [3,41,4,5]
12,43 129012 91 [1,2]
1000101 33434,34 1992 [3, 41,4,5]
结果:
1000101 33434.34 1992 [3,41,4,5]
12.43 129012 91 [1,2]
1000101 33434.34 1992 [3, 41,4,5]
关于python - 用逗号匹配 float ,然后用点替换逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24417149/