Python:在print语句中隐藏json空键值
这是我的第一个Python程序,通过json文件获取数据以构建科学引文:Python:在print语句中隐藏json空键值,python,Python,这是我的第一个Python程序,通过json文件获取数据以构建科学引文: .... js = json.loads(data) # here is an excerpt of my code: print("Journal articles:") for art in js['response']['docs']: stuff = art['docType_s'] if not stuff == 'ART': continue tit = art['title_s'][0]
....
js = json.loads(data)
# here is an excerpt of my code:
print("Journal articles:")
for art in js['response']['docs']:
stuff = art['docType_s']
if not stuff == 'ART': continue
tit = art['title_s'][0]
nom = art['authFullName_s'][0]
jou = art['journalTitle_s']
dat = art['producedDateY_i']
try:
pbm = art['pubmedId_s']
except (KeyError, NameError):
pbm = ""
print(nom,', ', tit, '. ', jou, '.', dat, '. Pubmed: ', pbm, sep="")
# sample output: J A. Anderson, Looking at the DNA structure, Nature, 2018. Pubmed: 3256988
到目前为止,它工作得很好,只是我不知道如何在键没有值的情况下从print语句中隐藏键值(即,对于一个特定引用,json文件中没有这样的键)
例如,一些科学引文没有“Pubmed”ID键/值(pmd)。我不想用空白值打印“Pubmed:”,而是想把它们都去掉:
# Desired output (when pbm key is missing from the JSON file):
# J A. Anderson, Looking at the DNA structure, Nature, 2018.
# NOT: J A. Anderson, Looking at the DNA structure, Nature, 2018. Pubmed:
我尝试了以下方法(如果值为空,则不打印pmd),但不起作用:
print('. Pubmed: ', pbm if pbm != "")
谢谢你的帮助。我认为最好/最干净的方法是使用“长”的
if/else
:
if pbm:
print(nom,', ', tit, '. ', jou, '.', dat, '. Pubmed: ', pbm, sep="")
else:
print(nom,', ', tit, '. ', jou, '.', dat, ', sep="")
您可以使用格式字符串使其更清晰:
if pbm:
print("%s, %s, %s. %s Pubmed: %s" % (nom, tit, jou, dat, pbm))
else:
print("%s, %s, %s. %s" % (nom, tit, jou, dat))
或者将格式字符串与三值。。。如果。。。否则…
:
print("%s, %s, %s. %s%s" % (nom, tit, jou, dat, ((" Pubmed: " + pbm) if pbm else "")))
然而,就我个人而言,我会选择第二个选项。您可以做以下操作:
js = json.loads(data)
print("Journal articles:")
for art in js['response']['docs']:
stuff = art['docType_s']
if not stuff == 'ART': continue
tit = art.get('title_s', None)[0]
nom = art.get('authFullName_s', None)[0]
jou = art.get('journalTitle_s', None)
dat = art.get('producedDateY_i', None)
pbm = art.get('pubmedId_s', None)
l = []
for e in (tit, nom, jou, dat, pbm):
if e:
if e is pbm:
l.append('Pubmed: ' + str(e))
else:
l.append(str(e))
pub = ', '.join(l).strip(', ')
print(pub)
这里使用的魔力在于dict对象提供给我们的get
函数。通过这种方式,您可以在dict中不存在特定键的情况下定义默认值(您的JSON对象只是Python中的dict)。在使用该方法时,您可以避免编写大量的if
s,并且仍然可以使用某种程度上可扩展且安全的方法来构建字符串。另外,你不需要两次询问你的口述
如果将来JSON结果将包含更多字段,您只需将它们添加到此集合中即可
...
for e in (tit, nom, jou, dat, pbm): #<-- insert more values here
...
。。。
对于e-in(tit,nom,jou,dat,pbm):#你几乎做对了强>
除了内联if语句需要有else条件so
改变这个
print(nom',,tit',jou',dat',.Pubmed:',pbm,sep=“”)
至
print(nom,,,,,tit,,,,jou,,,dat,,,.Pubmed:“如果len(pbm)!=0 else”,“如果len(pbm)!=0 else”,“sep=”“)
因此,如果没有Pubmed密钥,则pbm将为“”,len(pbm)为0。(您也可以使用pbm=“”)。在这些情况下,不会打印“Pubmed:‘value’” 您可以使用if-pbm:print(“某物”)它是否总是Pubmed
ID,或者其他一些字段(如日记或标题)是否也会丢失?谢谢您的帮助!如果您想添加更具体的键(如Pubmed键),该怎么办@Arno Nymous我想添加一个“vol”键(volume_s),还有一个名为“nom2”的第二个author键,它有一个索引:nom=art.get('authFullName_s',None)[1]
像“pmd”一样,这两个键可能并不总是在JSON字典中。我试图对另一个值(nom2=second author)做同样的操作但它不起作用,因为nom2是一个索引值:nom2=art['authFullName'][1]
我试过:print(nom','if len(nom2)!=0 else',vol if len(nom2)!=0 else','tit','jou','dat',.Pubmed:'if len pbm!=0 else',pbm if len pbm(pbm)!=0 else',sep)
@reaganrewopop您是否使用了除nom2之外的try和检查值是否存在,就像您对pbm所做的那样。。。。。。。我不明白这里的逻辑,如果nom2为None,你需要删除vol变量?哎呀,我的意思是print(nom','if len(nom2)!=0 else',nom2 if len(nom2)!=0 else',','tit','jou','dat',.Pubmed:'if len(pbm)!=0 else',pbm if len pbm(pbm)!=0 else',sep=“”
-是的,我使用了try和except,但忘了添加“索引器”。它正在工作,谢谢!我想我花了太多时间在它上面,我应该休息一下;)