正則表達式可以用拼接形式 (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