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

 

posted on 2013-06-06 10:29  Samuel Yang  阅读(6837)  评论(0编辑  收藏  举报