如何在文本fi中提取与正则表达式匹配的行号

2024-04-29 08:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个关于统计机器翻译的项目,在这个项目中,我需要从一个POS标记的文本文件中提取与正则表达式匹配的行号(任何带有“out”粒子的非分隔短语动词),并将行号写入一个文件(在python中)。

我有一个正则表达式:'\w*\u VB。?\sout_RP'和我的POS标记的文本文件:“Corpus.txt”。 我想得到一个与上述正则表达式匹配的行号的输出文件,并且输出文件每行应该只有一个行号(没有空行),例如:

2个

5个

44个

到目前为止,我的剧本中只有以下内容:

OutputLineNumbers = open('OutputLineNumbers', 'w')
with open('Corpus.txt', 'r') as textfile:
    phrase='\w*_VB.?\sout_RP'
    for phrase in textfile: 

OutputLineNumbers.close()

你知道怎么解决这个问题吗?

提前,谢谢你的帮助!


Tags: 文件项目标记postxtcorpusopenrp
2条回答

如果正则表达式对grep友好,那么可以直接使用bash。使用“-n”显示行号

例如:

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

将输出第一个包含行号的匹配行

2569:vote2012
2570:30
2574:118
2576:7248
2578:2293
2580:9594
2582:577

这应该可以解决您的问题,假设您在变量“phrase”中有正确的regex

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 )

相关问题 更多 >