【发布时间】:2020-03-05 01:18:20
【问题描述】:
我在 python 中有一个字符串(不是原始的),类似于以下内容:
Plenary Papers (1)
Peer-reviewed Papers (113)
PLENARY MANUSCRIPTS (1)
First Author Index
Harrer
Plenary Papers
One Some title
John W. Doe
2018 Physics SOmething Proceedings
Full Text: Download PDF - PER-Central Record
Show Abstract - Show Citation
PEER REVIEWED MANUSCRIPTS (113)
First Author Index
Doe · Doe2 · Doe3 · Jonathan
Peer-reviewed Papers
Two some title
Alex White, Paul Klee, and Jacson Pollock
2018 Physics Research Conference Proceedings, doi:10.1234/perc.2018.pr.White
Full Text: Download PDF - PER-Central Record
Show Abstract - Show Citation
Tree Some title
Suzanne Heck, Alex Someone, John I. Smith, and Andrew Bourgogne
2018 Physics Education Research Conference Proceedings, doi:10.2345/perc.2018.pr.Heck
Full Text: Download PDF - PER-Central Record
Show Abstract - Show Citation
..
我想抓取这三篇论文的元数据,即每个标题后面的那几行(例如“One Some title”、“John W. Doe”和 2018 Physics Something Proceedings”)。
我想在选择的开始和结束时使用两种模式:
'r"\n\n"' 和 'r"Show Abstract - Show Citation"'。
这(几乎)适用于https://regex101.com/使用这个正则表达式:
\n\n(.*?)Show Abstract - Show Citation
一个小问题是它对前两篇论文很贪心。
但不是在 python 中:
pattern=r"\n\n(.*?)Show Abstract - Show Citation"
re.findall(pattern, titles) #titles is the text above
#output is []
pattern_only_one_line=r"\nShow Abstract - Show Citation"
re.findall(pattern_only_one_line, titles)
#output shows three lines
这可能是原始字符串的另一个问题吗?
【问题讨论】:
-
您的正则表达式找不到匹配项 - regex101.com/r/X9AUw9/1
-
可能是链接有问题。 regex101.com/r/iN6pX6/193 有效吗?
-
您的正则表达式正在使用标志单行(点匹配换行符),因此您需要执行
re.findall(pattern, titles, re.DOTALL) -
@Wolph 是的,它正在工作!现在我想弄清楚如何在 .finditer 中使用它。如果需要,您可以添加答案