需要用python获得预期的输出(在描述中解释了问题)

2024-05-16 13:46:16 发布

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

我正在用python中的正则表达式开发一个数据提取器。 我在某个地方卡住了我在regex中创建的其他代码正在运行,但是下面提到了这个代码:

正则表达式代码:

regexCode='^about_company:\n[\s\S]+?[A-Z]:'

当我在python中运行时,上面的代码工作不正常,我想我犯了一个错误,因为regex代码运行正常here

预期输出:

The output should look like this is terminal of pycharm

抱歉的链接,我不能把照片直接因为声誉问题

Python代码:

import re

filename = open('textFile.txt','r')
rege = '^about_company:[\s\S]+?[A-Z]:|ABOUT COMPANY:[\s\S]+?[A-Z]:'
for data in filename:
    matches = re.findall(rege, data, re.MULTILINE)
    if matches:
        print(matches)

当我试图通过将数据存储到文本中来打印数据时,它起了作用,但当我试图从文件中读取数据时,它会显示空列表。 文本文件与regex101的链接中的相同。 我需要解决这个问题,请帮忙


Tags: 数据代码redata链接地方错误filename
1条回答
网友
1楼 · 发布于 2024-05-16 13:46:16

将整个文件读入内存并对整个文本运行regex:

import re

f = open('28985133.dat','r')
data = f.read()                # Read the file contents into a var
rege = r'^about_company:[\s\S]+?[A-Z]:|ABOUT COMPANY:[\s\S]+?[A-Z]:'
matches = re.findall(rege, data, re.MULTILINE) # Collect matches
for s in matches:              # Loop through matches
    print(s)                   # Print matches

相关问题 更多 >