Python 正則表達式 引入變量


正則表達式可以用拼接形式 (r' ' + str(i) + ' ') 來引入變量i

python hello.py fileopen.tgff 2

找到fileopen.tgff 中符合 From t0_(\S*) TO t0_(\S*) 和 From t1_(\S*) TO t1_(\S*) 形式並提取group(1)和(2)分別寫入文件t0.csv和t1.csv。

#!/usr/bin/python
#argv[1] is a filename; argv[2] is the number of graph
import re,sys,string
fp = open(sys.argv[1], "r")
all = fp.read()
fp.close
for i in range(int(sys.argv[2])):
        pattern2 = re.compile(r'FROM\s*t' + str(i) + '_(\S*)\s*TO\s*t' + str(i) + '_(\S*)')
        fp_o = open('t' + str(i) + '.csv', "w")
        fp_o.write('Source,Target\n')
        for match2 in pattern2.finditer(all):
                print match2.group(1,2)
                fp_o.write(match2.group(1) + ',' + match2.group(2) + '\n')
        fp_o.close

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM