Python:使用正则表达式查找最后一对出现的情况

标签 python regex

附件是text file我想解析。我想选择最后出现的单词组合中的文本:

  • (1)第7项管理层讨论分析

  • (2)第8项财务报表

我通常会使用正则表达式,如下所示:

re.findall(r"Item(?:(?!Item).)*7(?:(?!Item|7).)*Management(?:(?!Item|7|Management).)*Analysis[\s\S]*Item(?:(?!Item).)*8(?:(?!Item|8).)*Financial(?:(?!Item|8|Financial).)*Statements",text, re.DOTALL)

您可以在文本文件中看到,第 7 项和第 8 项的组合经常出现,但如果我找到最后一个匹配项 (1) 和最后一个匹配项 (2),我会大大增加获取所需文本的概率.

我的文本文件中所需的文本开头为:

"'This Item 7, Management's Discussion and Analysis of Financial Condition and Results of Operations, and other parts of this Form 10-K contain forward-looking statements, within the meaning of the Private Securities Litigation Reform Act of 1995, that involve risks and..... "

并以以下内容结尾:

"Item 8. Financial Statements and Supplementary Data"

如何调整我的正则表达式代码以获取第 7 项和第 8 项之间的最后一对?

更新:

我也尝试解析这个file使用相同的元素。

最佳答案

此代码已被重写。现在,它可以使用原始数据文件 (Output2.txt) 和新添加的数据文件 (Output2012.txt)。

import re

discussions = []
for input_file_name in ['Output2.txt', 'Output2012.txt']:
    with open(input_file_name) as f:
        doc = f.read()

    item7 = r"Item 7\.*\s*Management.s Discussion and Analysis of Financial Condition and Results of Operations"
    discussion_text = r"[\S\s]*"
    item8 = r"Item 8\.*\s*Financial Statements"

    discussion_pattern = item7 + discussion_text + item8
    results = re.findall(discussion_pattern, doc)

    # Some input files have table of contents and others don't 
    # just keep the last match
    discussion = results[len(results)-1]

    discussions.append((input_file_name, discussion))

discuss 变量包含每个数据文件的结果。

<小时/>

这是最初的解决方案。它不适用于新文件,但显示命名组的使用。我对这里的 StackOverflow 协议(protocol)不熟悉。我应该删除这个旧代码吗?

通过使用更长的匹配字符串,第 7 项的匹配数可以减少到只有 2 个 第 8 项 - 目录和实际部分。

因此搜索第二次出现的第 7 项,并保留所有文本直到第 8 项。此代码使用 Python 命名组。

import re

with open('Output2.txt') as f:
    doc = f.read()

item7 = r"Item 7\.*\s*Management.s Discussion and Analysis of Financial Condition and Results of Operations"
item8 = r"Item 8\.*\s*Financial Statements"

discussion_pattern = re.compile(
    r"(?P<item7>" + item7 + ")"
    r"([\S\s]*)"
    r"(?P<item7heading>" + item7 +")"
    r"(?P<discussion>[\S\s]*)"
    r"(?P<item8heading>" + item8 + ")"
)       

match = re.search(discussion_pattern, doc)
discussion = match.group('discussion')

关于Python:使用正则表达式查找最后一对出现的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052343/

相关文章:

java - 替换 Java 中第一次出现的特定模式

python - 调用类方法作为初始化的一部分

Java 正则表达式模式将日期格式拉至第一个正斜杠

java - 正则表达式,仅包含小写或大写字符或两者,用于用户名验证

javascript - 正则表达式:匹配多个单词的第一个字母

java - 使用 split ("|"通过管道符号拆分 Java 字符串)

python - 正确使用SkipTo

python - 给定两个 "if"语句,如果没有执行则执行一些代码

python - 对数据框进行均等切片并以不同名称存储

python - lib2to3 架构文档