我刚刚接触 Python,碰巧我需要从一些科学论文中提取一些信息。
如果给出如下纯文本:
- 简介
一些长文 - 方法论
一些长文 - 结果
一些长文
如何将一篇论文放入字典中,如下所示?
paper_1 = {
'Introduction': some long writings,
'Methodology': some long writings,
'Results': some long writings
}
非常感谢:-)
尝试后,我运行了一些代码,但它不能完美运行:
text = 'introduction This is the FIRST part.' \
'Methodologies This is the SECOND part.' \
'results This is the THIRD part.'
import re
from re import finditer
d={}
first =[]
second =[]
title_list=[]
all =[]
for match in finditer("Methodology|results|methodologies|introduction|", text, re.IGNORECASE):
if match.group() is not '':
title = match.group()
location = match.span()
first.append(location[0])
second.append(location[1])
title_list.append(title)
all.append(first)
all.append(second)
a=[]
for i in range(2):
j = i+1
section = text[all[1][i]:all[0][j]]
a.append(section)
for i in zip(title_list, a):
d[i[0]] = i[1]
print (d)
这将产生以下结果:
{
'introduction': ' This is the FIRST part.',
'Methodologies': ' This is the SECOND part.'
}
但是,
i) 它无法提取最后一位,即结果部分。
ii).在循环中,我给 range() 函数输入 2,因为我知道只有 3 个部分(简介、方法论和结果),但在某些论文中,人们会添加更多部分,我如何自动为范围()?例如,某些论文可能包含以下部分:- 简介
一些长文 - 某事的一般背景
一些长文 - 某种部分标题
一些长文 - 方法论
一些长文 - 结果
一些长文
三)。有没有更有效的方法可以在每个循环中构建字典?所以我不需要使用第二个循环。
2018年3月30日更新:
代码更新如下:
def section_detection(text):
title_list=[]
all =[[],[]]
dic={}
count = 0
pattern = '\d\. [A-Z][a-z]*'
for match in finditer(pattern, text, re.IGNORECASE):
if match.group() is not '':
all[0].append(match.span()[0])
all[1].append(match.span()[1])
title_list.append(match.group())
count += 1
for i in range(count):
j = i+1
try:
dic[title_list[i]]=text[all[1][i]:all[0][j]]
except IndexError:
dic[title_list[i]]=text[all[1][i]:]
return dic
如果执行如下:
import re
from re import finditer
text = '1. introduction This is the FIRST part.' \
'2. Methodologies This is the SECOND part.' \
'3. results This is the THIRD part.'\
'4. somesection This SOME section'
dic = section_detection(text)
print(dic)
给予:
{'1. introduction': ' This is the FIRST part.', '2. Methodologies': ' This is the SECOND part.', '3. results': ' This is the THIRD part.', '4. somesection': ' This SOME section'}
非常感谢大家! :-)
最佳答案
试试这个:
text = 'introduction This is the FIRST part. ' \
'Methodologies This is the SECOND part. ' \
'results This is the THIRD part. ' \
import re
kw = ['methodology', 'results', 'methodologies', 'introduction']
pat = re.compile(r'(%s)' % '|'.join(kw), re.IGNORECASE)
sp = [x for x in re.split(pat, text) if x]
dic = {k:v for k,v in zip(sp[0::2],sp[1::2])}
print(dic)
但这只是为了您的示例,在现实世界的文档中不要过多。你没有具体说明,“引言”之前的文字呢?有人用纯文本提到“结果”呢?
关于python - 用Python提取科学论文信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49542962/