我有一个包含82个段落的pdf文件,我的目标是使用python将每个段落分成自己的文本块。我已经使用PyPDF2提取了文本。
所有段落均以数字和句点开头(1. 42. 76.等)。它适用于大多数使用以下代码的段落,但并不总是考虑句点。例如,数字18的匹配输出为:“ 18(06 /”。这不应该被接受,因为它后面没有一段句号。有什么建议吗?
寻找职位的代码:
i = 1
all_positions = []
found = "found"
while found == "found":
matches = []
matches_positions =[]
standard_length = 0
substring = str(i) + "."
matches = re.finditer(substring, text, re.IGNORECASE)
matches_positions = [match.start() for match in matches]
standard_length = len(matches_positions)
if standard_length > 0:
all_positions.append(matches_positions[0])
i += 1
else:
found = "not found"
打印输出代码:
for i in range(0,len(all_positions)):
print('---')
print(text[all_positions[i]:all_positions[i+1]])
答案 0 :(得分:1)
您可以使用下面的正则表达式来达到目的:
^\d+\. ?(.*)
上述正则表达式的解释:
^
-表示给定测试字符串的开始。
\d+
-一次或多次匹配数字[0-9]。
\.
-从字面上匹配点。
?
-表示零或一个空格字符。
(.*)
-代表捕获组,它贪婪地捕获段落文本。
您可以找到正则表达式演示here.
在PYTHON中的实现:
import re
pattern = re.compile(r"^\d+\. ?(.*)", re.MULTILINE)
match = pattern.findall("1. Hellow World\n"
"23. This is loremIpsum text\n"
"9001. Some random textbcjsbcskcbksck sbcksbcksckscsk\n"
"90 (89. Some other")
print (match)
# Output - ['Hellow World', 'This is loremIpsum text', 'Some random textbcjsbcskcbksck sbcksbcksckscsk']
您可以找到上述代码here.
的实现