在两个点之间提取文本,由一个麻木的

2024-04-24 11:06:30 发布

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

我基本上已经阅读了PDF文件的内容。现在,我想弄清楚标题。一致性是-每个标头采用以下模式: "1. 我的头球。接下来的文字是……”

例如:

x = '1. Some Header. and some more text 2. Another Header. And that is the end'
import re
re.findall((r'[0-9]\..*\.'),x)

我试过了,但没成功。你知道吗

我希望的是: 最佳案例:['1。一些标题“,”2。另一个标题'] 最坏情况:['Some Header','Another Header']


Tags: and文件re标题内容pdf模式another
3条回答

你可以用

\d+\.[^.]+\.

enter image description here


x = '1. Some Header. and some more text 2. Another Header. And that is the end'
import re
re.findall((r'\d+\.[^.]\.'),x)

^{}

您可以使用re.findall

import re
x = '1. Some Header. and some more text 2. Another Header. And that is the end'
result = re.findall('\d+\.\s+[\w\s]+(?=[\.$])', x)

输出:

['1. Some Header', '2. Another Header']

如果标头应该从1开始,则可以使用捕获组:

(?<!\S)([1-9][0-9]*\.[^.]+)\.

Regex demo

你还能用吗

(?<!\S)(\d+\.[^.]+)\.

解释

  • (?<!\S)断言直接在左边的不是非空格字符
  • (捕获组1
    • \d+\.[^.]+匹配1+个数字、点和除点以外的任何字符的1+倍
  • )\.关闭组1并匹配一个点

Regex demo| Python demo

例如使用关于芬德尔你知道吗

import re 

regex = r"(?<!\S)(\d+\.[^.]+)\." 
test_str = "1. Some Header. and some more text 2. Another Header. And that is the end"

print(re.findall(regex, test_str))

结果

['1. Some Header', '2. Another Header']

相关问题 更多 >