首页 > 解决方案 > sed 到 python 替换额外的分隔符

问题描述

sed 's/\t/_tab_/3g'

我有一个 sed 命令,它基本上替换了我的文本文档中所有多余的制表符分隔符。我的文档应该是 3 列,但偶尔会有一个额外的分隔符。我无法控制这些文件。

我使用上面的命令来清理文档。但是我对这些文件的所有其他操作都在 python 中。有没有办法在 python 中执行上述 sed 命令?

样本输入:

Column1   Column2         Column3
James     1,203.33        comment1
Mike      -3,434.09       testing testing 123
Sarah     1,343,342.23    there   here

样本输出:

Column1   Column2         Column3
James     1,203.33        comment1
Mike      -3,434.09       testing_tab_testing_tab_123
Sarah     1,343,342.23    there_tab_here

标签: pythoncsvsed

解决方案


您可以逐行读取文件,使用制表符拆分,如果超过 3 个项目,则将第 3 个项目之后的项目用_tab_:

lines = []
with open('inputfile.txt', 'r') as fr:
    for line in fr:
        split = line.split('\t')
        if len(split) > 3:
            tmp = split[:2]                      # Slice the first two items
            tmp.append("_tab_".join(split[2:]))  # Append the rest joined with _tab_
            lines.append("\t".join(tmp))         # Use the updated line
        else:
            lines.append(line)                   # Else, put the line as is

查看Python 演示

lines变量将包含类似

Mike    -3,434.09   testing_tab_testing_tab_123
Mike    -3,434.09   testing_tab_256
No  operation   here

推荐阅读