前言
由于毕业论文格式要求英文参考文献的题目的每个单词(除了介词)的首字母都要大写,如果一条条地自己修改费时费力,这里就想着简单地用python操作字符串的方式实现。
实现思路
-
观察bib参考文献格式,可以发现题目标识的关键字为
title
@article{ ames2016control, title={ Control barrier function based quadratic programs for safety critical systems}, author={ Ames, Aaron D and Xu, Xiangru and Grizzle, Jessy W and Tabuada, Paulo}, journal={ IEEE Transactions on Automatic Control}, volume={ 62}, number={ 8}, pages={ 3861--3876}, year={ 2016}, publisher={ IEEE} }
-
创建一个介词列表,将不需要首字母大写的单词添加进去,然后依次读取文件的每一行,判断是否是
title
一行,如果是,检查该行字符串单词首字母是否已全部大写,如果没有则使用title()
函数进行首字母大写的修改。 -
完整python实现代码如下:
import numpy as np import string # 去除相关介词的大写 e_list = ['of', 'the', 'for', 'with', 'and', 'in', 'to', 'on', 'at'] def new_str(x): """将字符串中的单词(除去预先给定的单词列表)首字母大写 Args: x (_type_): 预处理字符串 Returns: _type_: 除给定单词之外单词首字母大写后的字符串 """ return ' '.join([a.title() if (not a in e_list and not a.isupper()) else a for a in x.split()]) if __name__=='__main__': f = open('bib.bib', 'r', encoding='UTF-8') # 读取想要修改的bib参考文献 fw = open('bib_update.bib', 'w') # 写入新的bib文件中 lines = f.readlines() for line in lines: # if(line[2:7]=="title"): if("title" in line[0:10] and "booktitle" not in line[0:10]): new_line = line.replace('{', '{ {') new_line = new_line.replace('}', '}}') # print(new_line[0:9]) # final_line = new_line[0:9] + string.capwords(new_line[9:])+'\n' # final_line = new_line[0:9] + new_line[9:].title() final_line = new_line[0:9] + new_str(new_line[9:])+'\n' fw.write(final_line) print(final_line) else: fw.write(line) fw.close()
修改完成后的bib参考文献格式大致如下:
@article{
ames2016control,
title={
{
Control Barrier Function Based Quadratic Programs for Safety Critical Systems}},
author={
Ames, Aaron D and Xu, Xiangru and Grizzle, Jessy W and Tabuada, Paulo},
journal={
IEEE Transactions on Automatic Control},
volume={
62},
number={
8},
pages={
3861--3876},
year={
2016},
publisher={
IEEE}
}
代码仓库见GitHub。