我正在尝试使用正则表达式从PDF文本中提取数据字段。
案文是:
"SAMPLE EXPERIAN CUSTOMER\n2288150 - EXPERIAN SAMPLE REPORTS\nData Dictionary Report\nFiltered By:\nCustom Selection\nMarketing Element:\nPage 1 of 284\n2014-11-11 21:52:01 PM\nExperian and the marks used herein are service marks or registered trademarks of Experian.\n© Experian 2014 All rights reserved. Confidential and proprietary.\n**Data Dictionary**\nDate of Birth is acquired from public and proprietary files. These sources provide, at a minimum, the year of birth; the month is provided where available. Exact date of birth at various levels of detail is available for \n\n\n\n\n\nNOTE: Records coded with DOB are exclusive of Estimated Age (101E)\n**Element Number**\n0100\nDescription\nDate Of Birth / Exact Age\n**Data Dictionary**\n\n\n\n\n\n\n\n\n\n\nFiller, three bytes\n**Element Number**\n0000\n**Description**\nEnhancement Mandatory Append\n**Data Dictionary**\n\n\nWhen there is insufficient data to match a customer's record to our enrichment master for estimated age, a median estimated age based on the ages of all other adult individuals in the same ZIP+4 area is provided. \n\n\n\n\n\n\n00 = Unknown\n**Element Number**\n0101E\n**Description**\nEstimated Age\n"
字段名称以粗体显示。字段名称之间的文本是字段值。
我第一次尝试提取'描述'字段使用以下正则表达式:
pattern = re.compile('\nDescription\n(.*?)\nData Dictionary\n')
re.findall(pattern,text)
结果是正确的:
['Date Of Birth / Exact Age', 'Enhancement Mandatory Append']
但是使用相同的想法来提取数据字典' Field给出空结果:
pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n')
re.findall(pattern,text)
结果:
[]
知道为什么吗?
答案 0 :(得分:2)
.
与换行符不匹配。尝试:
pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n', flags=re.DOTALL)
re.findall(pattern,text)
请注意我将re.DOTALL
作为flags
参数传递给re.compile
。
答案 1 :(得分:1)
尝试在正则表达式中使用标记re.MULTILINE
:
pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n', re.MULTILINE)
re.findall(pattern,text)