簡體   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