python - 用逗号匹配 float ,然后用点替换逗号?

标签 python regex python-2.7

我有一个文本文件,其中包含一些不同类型的数字:整数、二进制和 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/

相关文章:

python - 使用单行代码合并两个具有不同索引的数据帧,同时保留主数据帧的索引

python - 如何使用 Flask-WTForms 以 DRY 方式创建重复的表单元素?

regex - 我可以在DynamoDB查询中使用正则表达式吗?

python - 通过将Python与OpenCV结合使用无法在Raspberry PI上保存视频

python - 理解 Python 递归

python - 使用 os.popen() 或子进程执行函数

regex - 使用正则表达式验证数据是否正确?

javascript - 在方程中的适当位置插入 * 的正则表达式

Python:PIP 安装路径,这个和其他插件的正确位置是什么?

python - 使用 Python 进行 SQL 注入(inject) (WordPress)