繁体   English   中英

sed to python取代了额外的分隔符

[英]sed to python replace extra delimiters in a

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

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

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
import os
os.system("sed -i 's/\t/_tab_/3g' " + file_path)

这有用吗? 请注意上面的sed命令有一个-i参数,用于修改输入文件。

你可以模仿python中的sed行为:

import re

pattern = re.compile(r'\t')
string = 'Mike\t3,434.09\ttesting\ttesting\t123'
replacement = '_tab_'
count = -1
spans = []
start = 2 # Starting index of matches to replace (0 based)
for match in re.finditer(pattern, string):
    count += 1
    if count >= start:
        spans.append(match.span())
spans.reverse()
new_str = string
for sp in spans:
     new_str = new_str[0:sp[0]] + replacement + new_str[sp[1]:]

现在new_str'Mike\\t3,434.09\\ttesting_tab_testing_tab_123'

您可以将其包装在一个函数中,并为每一行重复。 但请注意,此GNU sed行为不是标准的:

'NUMBER'仅替换REGEXP的第NUMBER个匹配。

  interaction in 's' command Note: the POSIX standard does not specify what should happen when you mix the 'g' and NUMBER modifiers, and currently there is no widely agreed upon meaning across 'sed' implementations. For GNU 'sed', the interaction is defined to be: ignore matches before the NUMBERth, and then match and replace all matches from the NUMBERth on. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM