How to extract lines numbers that match a regular expression in a text file

只愿长相守 提交于 2019-11-30 16:48:41
Kalyan02

This should solve your problem, presuming you have correct regex in variable 'phrase'

import re

# compile regex
regex = re.compile('[0-9]+')

# open the files
with open('Corpus.txt','r') as inputFile:
    with open('OutputLineNumbers', 'w') as outputLineNumbers:
        # loop through each line in corpus
        for line_i, line in enumerate(inputFile, 1):
            # check if we have a regex match
            if regex.search( line ):
                # if so, write it the output file
                outputLineNumbers.write( "%d\n" % line_i )

you can do it directly with bash if your regular expression is grep friendly. show the line numbers using "-n"

for example:

grep -n  "[1-9][0-9]" tags.txt

will output matching lines with the line numbers included at first

2569:vote2012
2570:30
2574:118
2576:7248
2578:2293
2580:9594
2582:577
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!