[精讚] [會員登入]
339

python 的RE

python re

分享此文連結 //n.sfs.tw/12349

分享連結 python 的RE@igogo
(文章歡迎轉載,務必尊重版權註明連結來源)
2018-04-24 15:03:38 最後編修
2018-04-20 11:29:47 By igogo
 

 

有多個記錄檔需要更動,  其中記錄檔主要內容長這樣

$ORIGIN 2.5.8.8.2.0.1.0.0.2.ip6.arpa.
$TTL 86400    ; 24 hours
@ SOA    dns.tc.edu.tw. nc-net.tc.edu.tw. (
      2018030603 ; serial
      36000    ; refresh (10 hours)
      3600     ; retry (1 hours)
      36000    ; expire (10 hours)
      43200    ; minimum (12 hours)
)
@ NS     dns.tc.edu.tw.
@ NS     dns2.tc.edu.tw.
@ NS     dns3.tc.edu.tw.

$ORIGIN 2.5.8.8.2.0.1.0.0.2.ip6.arpa.
0.0    NS    dns.tc.edu.tw.
0.0    NS    dns2.tc.edu.tw.
0.0    NS    dns3.tc.edu.tw.
3.2    NS    dns.hpes.tc.edu.tw.
4.2    NS    dns.kkes.tc.edu.tw.

 

 

0.0    NS    dns.tc.edu.tw.
0.0    NS    dns2.tc.edu.tw.
0.0    NS    dns3.tc.edu.tw.
3.2    NS    dns.hpes.tc.edu.tw.
4.2    NS    dns.kkes.tc.edu.tw.

 

想要改成

 

0.0    NS    dns.tc.edu.tw.
0.0    NS    dns2.tc.edu.tw.
0.0    NS    dns3.tc.edu.tw.
3.2    NS    dns.tc.edu.tw.
3.2    NS    dns2.tc.edu.tw.
3.2    NS    dns3.tc.edu.tw.
4.2    NS    dns.tc.edu.tw.
4.2    NS    dns2.tc.edu.tw.
4.2    NS    dns3.tc.edu.tw.

 

用RE來比對的原則如下

讀取每一行為line , 不符合蒐集  符合加工

 m = re.match("^[\d\w]\.[\d\w][\s|\t]+NS", line)

開頭第一個字元為數字或英文, 第二個為 .  第三個是數字或英文[\s|\t]+NS

NS前有可能是tab or space

 

前三行不動  數1,2,3, 其它送到nsfactory加工

import os
import re

files = (os.listdir("files"))


def nsfactory(line):
    content = ""

    for i in range(3):
        if (i == 0):
            content += "{}\tdns.tc.edu.tw.\n".format(line)
        if (i == 1):
            content += "{}\tdns2.tc.edu.tw.\n".format(line)
        if (i == 2):
            content += "{}\tdns3.tc.edu.tw.\n".format(line)
    return content


for file in files:
    filename = "files/{}".format(file)
    content = ""
    count = 0
    repeat = 0

    with open(filename) as fp:
        for line in fp:
            m = re.match("^[\d\w]\.[\d\w][\s|\t]+NS", line)
            if (m):
                count += 1
                if (count > 3):
                    # print(m.group())
                    content += nsfactory(m.group())
                else:
                    content += line

            else:
                # print(line)
                content += line

    filename = "ok/{}".format(file)
    with open(filename, "w") as fw:
        fw.write(content)
 

       

 

pythonre.zip

 

 

 

 

END

你可能感興趣的文章

00-F2 的 IPV6 反解設定 近日, 強者我的大神同事, line 傳來一句: igogo 上次你那個ipv6的設定檔 再幫我跑一次 如連結 程式都寫

找尋多個文件夾中最新檔案(jpg,png,txt)並複製到nexus資料夾 找尋多個文件夾中最新檔案(jpg,png,txt)並複製到集中資料夾

python 的RE python re

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

[vue.js] input event Form-Input-Components-using-Custom-Events

利用maven建立一個可執行的jar檔 利用maven建立一個可執行的jar檔

2018 hoc 掃地機器人 掃地機器人只能打掃沒有障礙物(桌椅、牆壁)的範圍,請寫程式控制機器人打掃餐廳的所有走道, 並在清掃完畢後回到充電器。

vim 特定範圍行數開頭加上# 註解 vim 特定範圍行數開頭加上# 註解

Arrays.asList 後想再add出現 UnsupportedOperationException 這個問題真是搞死我了 List<String> fruits = Arrays.asList("a