【问题标题】:How to extract lines numbers that match a regular expression in a text file如何提取与文本文件中的正则表达式匹配的行号
【发布时间】:2013-06-09 05:20:46
【问题描述】:

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

我有这个正则表达式:'\w*_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()

知道如何解决这个问题吗?

提前感谢您的帮助!

【问题讨论】:

    标签: python regex nlp part-of-speech


    【解决方案1】:

    这应该可以解决您的问题,假设您在变量“短语”中有正确的正则表达式

    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 )
    

    【讨论】:

    • 使用for line_i, line in enumerate(inputFile, 1) 会简化此操作。
    • 非常感谢。唯一我没有澄清的是该短语可能是句子的一部分,所以我将不得不使用 re.findall 而不是 re.match,这很有效!再次感谢:-)
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多