Python 如何有效地提取遵循相同模式的特定数量和特定类型的字符串?
我想以相同的模式(author list.year.title.Journal)从出版物记录中提取年份和标题 例如,对于以下出版物记录Python 如何有效地提取遵循相同模式的特定数量和特定类型的字符串?,python,regex,Python,Regex,我想以相同的模式(author list.year.title.Journal)从出版物记录中提取年份和标题 例如,对于以下出版物记录text: text=['Axley, J. 1988. Progress Toward a General Analytical Method for Predicting Indoor Air Pollution in Buildings: Indoor Air Quality Modeling Phase III Report. Gaithersburg,
text
:
text=['Axley, J. 1988. Progress Toward a General Analytical Method for Predicting Indoor Air Pollution in Buildings: Indoor Air Quality Modeling Phase III Report. Gaithersburg, Maryland: National Bureau of Standards, NBSIR 88-3814.',
'Bearg, D.W. 1994. Second Generation Demand-Controlled Ventilation Systems. Proceedings of ASHRAE IAQ 94: 169-174.',
'Berg-Munch, B., G. Clausen and P.O. Fanger. 1986. Ventilation Requirements for the Control of Body Odor in Spaces Occupied by Women. Environment International 12: 195-199.']
预期产出将是:
['1988'、'1994'、'1986']
和
[“预测建筑物室内空气污染的通用分析方法进展:室内空气质量建模第三阶段报告”,“第二代需求控制通风系统”,“控制女性居住空间气味的通风要求”]
我正在尝试使用正则函数。我的代码很长,但可以提取预期的输出。我想知道如何有效地做到这一点
newline=[]
for line in range(len(text)):
key=text[line]
p1=r"[0-9][0-9][0-9][0-9]\..+?\."
pattern1 = re.compile(p1)
newline.append("".join(pattern1.findall(key)))
year = [x.split('.')[0] for x in newline]
title = [y.split('.')[1] for y in newline]
您可以使用2个捕获组:
\s(\d{4})\.\s*(.+)
正则表达式解释:
:匹配空白\s
:匹配捕获组#1中的4位数字(\d{4})
:匹配一个点\。
:匹配0个或多个空格\s*
:匹配捕获组2中任意字符的1+(.+)
>>重新导入
>>>text=['Axley,J.1988.建筑物室内空气污染预测通用分析方法的进展:室内空气质量建模第三阶段报告。马里兰州盖瑟斯堡:国家标准局,NBSIR 88-3814,
“Bearg,D.W.1994。第二代需求控制通风系统。ASHRAE IAQ会议录94:169-174。”,
“Berg Munch,B.,G.Clausen和P.O.Fanger.1986.女性居住空间中控制体味的通风要求.国际环境12:195-199.”
>>>年份=[]
>>>标题=[]
>>>对于文本中的s:
... m=重新搜索(r'\s(\d{4})\.\s*(.+)',s)
... 如果(m):
... 年份。追加(m.group(1))
... 标题.附加(m.group(2))
...
>>>印刷品(年)
['1988', '1994', '1986']
>>>印刷品(标题)
[
“预测建筑物室内空气污染的通用分析方法进展:室内空气质量建模第三阶段报告。马里兰州盖瑟斯堡:国家标准局,NBSIR 88-3814。”,
“第二代需求控制通风系统。ASHRAE IAQ会议录94:169-174。”,
“女性居住空间中控制体味的通风要求。国际环境12:195-199。”
]
你熟悉捕捉括号吗?它简洁明了!