如何使用python基于引用键从bibtex文件中删除特定条目?我基本上想要一个带有两个参数的函数(bibtex文件和引用键的路径)并删除与文件中的键对应的条目。我玩正则表达式但没有成功。我也看了一下bibtex解析器,但这似乎有点矫枉过正。在下面的骨架函数中,决定性部分是content_modified =
。
def deleteEntry(path, key):
# get content of bibtex file
f = open(path, 'r')
content = f.read()
f.close()
# delete entry from content string
content_modified =
# rewrite file
f = open(path, 'w')
f.write(content_modified)
f.close()
这是一个示例bibtex文件(摘要中有空格):
@article{dai2008thebigfishlittlepond,
title = {The {Big-Fish-Little-Pond} Effect: What Do We Know and Where Do We Go from Here?},
volume = {20},
shorttitle = {The {Big-Fish-Little-Pond} Effect},
url = {http://dx.doi.org/10.1007/s10648-008-9071-x},
doi = {10.1007/s10648-008-9071-x},
abstract = {The big-fish-little-pond effect {(BFLPE)} refers to the theoretical prediction that equally able students will have lower academic
self-concepts in higher-achieving or selective schools or programs than in lower-achieving or less selective schools or programs,
largely due to social comparison based on local norms. While negative consequences of being in a more competitive educational
setting are highlighted by the {BFLPE}, the exact nature of the {BFLPE} has not been closely scrutinized. This article provides
a critique of the {BFLPE} in terms of its conceptualization, methodology, and practical implications. Our main argument is that
of the {BFLPE.}},
number = {3},
journal = {Educational Psychology Review},
author = {Dai, David Yun and Rinn, Anne N.},
year = {2008},
keywords = {education, composition by performance, education, peer effect, education, school context, education, social comparison/big-fish{\textendash}little-pond effect},
pages = {283--317},
file = {Dai_Rinn_2008_The Big-Fish-Little-Pond Effect.pdf:/Users/jpl2136/Documents/Literatur/Dai_Rinn_2008_The Big-Fish-Little-Pond Effect.pdf:application/pdf}
}
@book{coleman1966equality,
title = {Equality of Educational Opportunity},
shorttitle = {Equality of educational opportunity},
publisher = {{U.S.} Dept. of Health, Education, and Welfare, Office of Education},
author = {Coleman, James},
year = {1966},
keywords = {\_task\_obtain, education, school context, soz. Ungleichheit, education}
}
编辑:这是我提出的解决方案。它不是基于匹配整个bibtex条目,而是查找所有开头@article{dai2008thebigfishlittlepond,
,然后通过切片上下文字符串来删除相应的条目。
content_keys = [(m.group(1), m.start(0)) for m in re.finditer("@\w{1,20}\{([\w\d-]+),", content)]
idx = [k[0] for k in content_keys].index(key)
content_modified = content[0:content_keys[idx][1]] + content[content_keys[idx + 1][1]:]
答案 0 :(得分:1)
正如Beni Cherniavsky-Paskin在评论中提到的那样,你将不得不依赖这样一个事实,即你的BibTex条目将在行开始后立即开始和结束(没有任何制表符或空格)。然后你可以这样做:
pattern = re.compile(r"^@\w+\{"+key+r",.*?^\}", re.S | re.M)
content_modified = re.sub(pattern, "", content)
注意两个修饰符。 S
会使.
个匹配行中断。 M
使^
在字符串的开头匹配。
如果你不能依赖这个事实,那么BibTex格式根本就不是一种常规语言(因为它允许{}
的嵌套,这必须被计算为正确的结果。有正则表达式的味道,可能仍然这个任务可能(使用递归或平衡组),但我认为Python不支持这些功能。因此,你实际上必须使用BibTex解析器(这也会使你的代码更加明显,我猜)。 p>