在python中写出匹配的行

时间:2014-03-13 16:05:49

标签: python regex

我正在尝试打印匹配模式的行并写出匹配的行。

匹配行的编号很好,但是,Python也没有在新文件中写入内容,也没有引发错误消息。

#!/usr/bin/env python
import re
outputLineNumbers = open('OutputLineNumbers', 'w')
outputLine = open('OutputLine', 'w')
inputFile = open('z.vcf','r')
matchLines = inputFile.readlines()    


total = 0
for i in range(len(matchLines)):
    line = matchLines[i]
#print out the matched line number    
    if re.match('(\w+)\|(\d+)\|(\w+)\|AGTA(\d+)\.(\d)\|\s(0+\d+)\s\.\s(\w)\s(\w),(\w)', line):
        total += 1
        outputLineNumbers.write( str(i+1) + "\n" )
#WRITE out the matched line
    if line == ('(\w+)\|(\d+)\|(\w+)\|AGTA(\d+)\.(\d)\|\s(0+\d+)\s\.\s(\w)\s(\w),(\w)'):
        outputLine.write( line + "\n" )
print "total polyploid marker is : ", total


outputLineNumbers.close()
inputFile.close()
outputLine.close()

1 个答案:

答案 0 :(得分:2)

您试图测试该行是否等于模式:

if line == ('(\w+)\|(\d+)\|(\w+)\|AGTA(\d+)\.(\d)\|\s(0+\d+)\s\.\s(\w)\s(\w),(\w)'):

但是,当字符串看起来包含模式时,字符串相等性不会神奇地调用正则表达式引擎。

删除if line ==测试,然后将匹配的行写出作为前一个if块的一部分:

if re.match('(\w+)\|(\d+)\|(\w+)\|AGTA(\d+)\.(\d)\|\s(0+\d+)\s\.\s(\w)\s(\w),(\w)', line):
    total += 1
    outputLineNumbers.write( str(i+1) + "\n" )
    #WRITE out the matched line
    outputLine.write( line + "\n" )

请注意,您可以直接遍历matchLines ;请使用enumerate() function来生成运行索引:

for i, line in enumerate(matchLines, 1):
    if re.match('(\w+)\|(\d+)\|(\w+)\|AGTA(\d+)\.(\d)\|\s(0+\d+)\s\.\s(\w)\s(\w),(\w)', line):
        total += 1
        outputLineNumbers.write("{}\n".format(i))

其中i从1开始,因此之后无需再添加1。

相关问题