[精讚] [會員登入]
319

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則留言。

訪客留言

[無留言]

隨機好文

windows ad 如何得知 dn 值 如何得知 windows ad 上的使用者dn 值 https://support.symantec.com/en_US

臺中市校務雲端系統與Windows AD帳號整合(1) active directory,ldaps,雲端校務系統

[scratch2] 巢狀迴圈 有兩清單 一數字 一英文 想排出所以可能, 例如1a,1b,1c,2a,2b,2c...3c 利用巢狀迴圈 內圈累加的變

scratch3 計算得分排名 scratch3 得分排名

刪除資料夾內的檔案 lambda 一行文 Arrays.stream(new File("/folder/path").