我一直在开发一个函数,它可以从一个打开的文本文件中更新两个字典(类似的作者,以及他们获得的奖项)。文本文件如下所示:
Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur
Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas
等等。名字是作者的名字(姓第一,姓最后),然后是他们可能获得的奖项,然后是与他们相似的作者。到目前为止我得到的是:
def load_author_dicts(text_file, similar_authors, awards_authors):
name_of_author = True
awards = False
similar = False
for line in text_file:
if name_of_author:
author = line.split(', ')
nameA = author[1].strip() + ' ' + author[0].strip()
name_of_author = False
awards = True
continue
if awards:
if ',' in line:
awards = False
similar = True
else:
if nameA in awards_authors:
listawards = awards_authors[nameA]
listawards.append(line.strip())
else:
listawards = []
listawards.append(line.strip()
awards_authors[nameA] = listawards
if similar:
if line == '\n':
similar = False
name_of_author = True
else:
sim_author = line.split(', ')
nameS = sim_author[1].strip() + ' ' + sim_author[0].strip()
if nameA in similar_authors:
similar_list = similar_authors[nameA]
similar_list.append(nameS)
else:
similar_list = []
similar_list.append(nameS)
similar_authors[nameA] = similar_list
continue
这太好了!但是,如果文本文件包含一个只有名字的条目(即没有奖项,也没有类似的作者),它会把整个事情搞砸,在这个部分生成一个IndexError: list index out of range
)我怎样才能解决这个问题?也许在那个区域有个'try, except function'
?
另外,我也不介意去掉那些continue函数,我不知道怎样才能让它继续运行。我对这个还很陌生,所以任何帮助都将不胜感激!我一直在尝试一些东西,它改变了另一个我不想改变的部分,所以我想我应该问问专家。你知道吗
这样做怎么样,只是为了获取数据,然后以任何你想要的方式操作字典。你知道吗
你知道吗测试.txt包含您的数据
还有我的代码来解析它。你知道吗
奖励_解析.py你知道吗
相关问题 更多 >
编程相关推荐