#####为什么会报错呀,该怎么改呢
#####运行结果显示这样
Traceback (most recent call last):
File "E:\pychramproject\实验8.3a.py", line 33, in <module>
if not sort_title(ref):
File "E:\pychramproject\实验8.3a.py", line 32, in sort_title
return re.search(r'#(.*?)\.', ref).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
import re
# 原始文本
ref = """[1] Panos Achlioptas, Olga Diamanti, Ioannis Mitliagkas, and
Leonidas Guibas. Learning representations and generative
models for 3D point clouds. In Proc. ICML, 2018
[2] Pulkit Agrawal, Joao Carreira, and Jitendra Malik. Learning
to see by moving. In Proc. ICCV, 2015
[3] Peter N. Belhumeur, David J. Kriegman, and Alan L. Yuille.
The bas-relief ambiguity. IJCV, 1999
[4] Christoph Bregler, Aaron Hertzmann, and Henning Biermann.
Recovering non-rigid 3D shape from image streams. In Proc.
CVPR, 2000
[5] Angel X. Chang, Thomas Funkhouser, Leonidas Guibas.
Shapenet: An information-rich 3d model reposi-tory.
arXiv preprint arXiv:1512.03012, 2015
[6] Ching-Hang Chen, Ambrish Tyagi, Amit Agrawal, Dy-lan
Drover, Rohith MV, Stefan Stojanov, and James M.
Rehg. Unsupervised 3d pose estimation with geometric self-supervision.
In Proc. CVPR, 2019"""
# 将文本中的"[x]"标记替换成"$[x]",以后面的"$"作为分隔符
ref_str = re.sub(r'\[([0-9]{1})\]', r'$[\1]', ref)
# 将文本中的"xx."替换成"xx.#",以后面的"#"作为分隔符
ref_str_2 = re.sub(r'([a-zA-Z]{2})\.', r'\1.#', ref_str)
# 将每篇参考文献拆分到一个列表中
ref_str2 = ref_str_2.replace("\n", "")
ref_list = ref_str2.split("$")
# 定义一个函数,用于排序时作为key参数传入
def sort_title(ref):
# 分割出参考文献标题并返回
return re.search(r'#(.*?)\.', ref).group(1)
# 按照参考文献标题排序
ref_sort_by_title = sorted(ref_list, key=sort_title)
print("按参考文献标题排序:")
for ref in ref_sort_by_title:
print(ref)
# 定义一个函数,用于排序时作为key参数传入
def sort_year(ref):
# 分割出出版年份并返回,注意取值是负数
return int(re.search(r', ([0-9]{4})', ref).group(1))
# 按照出版年份排序
ref_sort_by_year = sorted(ref_list, key=sort_year)
print("\n按出版年份排序:")
for ref in ref_sort_by_year:
print(ref)
说明当前正则表达式找不到匹配的结果。可以检查表达式是否有误,或者用它匹配的字符串是否有误。避免报错可以加上try:...except:...代码块