Python regexp模块重新

时间:2017-10-23 17:11:16

标签: python regex

是否有任何更改将" Customer-01" " Cust-02" 添加到最后一列(与python regexp)喜欢" 预期输出部分"下面?

示例:

Customer-01
192.168.12.100  61212 10    18w3d    00:00:37 00:00:22
192.168.12.120  61212 337   6d00h    00:00:07 00:00:06
192.168.12.130  61212 0     1w3d     00:00:42 00:00:54
192.168.12.140  61212 0     36w6d    00:00:14 00:00:22
192.168.12.150  61212 4     11w3d    00:00:24 00:00:22


Cust-02         
192.168.13.100  61212 10    18w3d    00:00:37 00:00:22
192.168.14.120  61212 337   6d00h    00:00:07 00:00:06
192.168.15.130  61212 0     1w3d     00:00:42 00:00:54
192.168.16.140  61212 0     36w6d    00:00:14 00:00:22
192.168.17.150  61212 4     11w3d    00:00:24 00:00:22

预期输出:

192.168.12.100  61212 10    18w3d    00:00:37 00:00:22 Customer-01
192.168.12.120  61212 337   6d00h    00:00:07 00:00:06 Customer-01
192.168.12.130  61212 0     1w3d     00:00:42 00:00:54 Customer-01
192.168.12.140  61212 0     36w6d    00:00:14 00:00:22 Customer-01
192.168.12.150  61212 4     11w3d    00:00:24 00:00:22 Customer-01


192.168.13.100  61212 10    18w3d    00:00:37 00:00:22 Cust-02  
192.168.14.120  61212 337   6d00h    00:00:07 00:00:06 Cust-02
192.168.15.130  61212 0     1w3d     00:00:42 00:00:54 Cust-02
192.168.16.140  61212 0     36w6d    00:00:14 00:00:22 Cust-02
192.168.17.150  61212 4     11w3d    00:00:24 00:00:22 Cust-02

1 个答案:

答案 0 :(得分:1)

我不会用正则表达式来做这件事。

  1. 通过双重换行将文本拆分为块
  2. 将第[1]行的第[0]行放到每个块的第[n]行
  3. 代码

    #!/usr/bin/env python
    
    """Adjust text according to example."""
    
    
    def adjust_text(text):
        blocks = text.split("\n\n\n")
        for block_nr, block in enumerate(blocks):
            lines = block.split("\n")
            for line_nr, _ in enumerate(lines):
                if line_nr != 0:
                    lines[line_nr] += "  " + lines[0]
            blocks[block_nr] = "\n".join(lines)
    
        text = "\n\n\n".join(blocks)
        return text
    
    
    if __name__ == '__main__':
        text = """Customer-01
    192.168.12.100  60000 10    18w3d    00:00:37 00:00:22 E  179/34634  9/1
    192.168.12.120  64524 337   6d00h    00:00:07 00:00:06 E  179/29837  0/0
    192.168.12.130  64522 0     1w3d     00:00:42 00:00:54 E  9835/179   0/0
    192.168.12.140  64512 0     36w6d    00:00:14 00:00:22 E  33883/179  0/0
    192.168.12.150  64512 4     11w3d    00:00:24 00:00:22 E  179/13712  4/0
    
    
    Cust-02
    192.168.13.100  64512 10    18w3d    00:00:37 00:00:22 E  179/34634  9/1
    192.168.14.120  64524 337   6d00h    00:00:07 00:00:06 E  179/29837  0/0
    192.168.15.130  64522 0     1w3d     00:00:42 00:00:54 E  9835/179   0/0
    192.168.16.140  64512 0     36w6d    00:00:14 00:00:22 E  33883/179  0/0
    192.168.17.150  64512 4     11w3d    00:00:24 00:00:22 E  179/13712  4/0"""
        text = adjust_text(text)
        print(text)