【问题标题】:Python: Hiding json empty key values with f-stringPython:用 f-string 隐藏 json 空键值
【发布时间】:2018-10-10 08:38:52
【问题描述】:

我使用 f 字符串而不是打印改进了 my first Python program

....
js = json.loads(data)

# here is an excerpt of my code:

def publi(type):
    if type == 'ART':
        return f"{nom} ({dat}). {tit}. {jou}. Pubmed: {pbm}"

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(publi('ART'))

此程序通过 json 文件获取数据以构建科学引文:

# sample output: J A. Anderson (2018). Looking at the DNA structure, Nature. PubMed: 3256988

它工作得很好,除了(再次)我不知道如何在键没有值时从 return 语句中隐藏键值(即,json 文件中没有针对一个特定引用的这样的键)。

例如,一些科学引文没有“Pubmed”键/值 (pmd)。我不想用空白值打印“Pubmed:”,而是想摆脱它们:

# Desired output (when pbm key is missing from the JSON file):
# J A. Anderson (2018) Looking at the DNA structure, Nature
# NOT: J A. Anderson (2018) Looking at the DNA structure, Nature. Pubmed: 

使用 publi 函数中的 print 语句,我可以编写以下内容:

# Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else ""

有谁知道如何使用 f-string 获得相同的结果?

感谢您的帮助。

PS:作为一个 python 初学者,仅仅阅读Using f-string with format depending on a condition 的帖子我无法解决这个特定的问题

【问题讨论】:

标签: python json f-string


【解决方案1】:

您也可以在 f 字符串中使用条件表达式:

return f"{nom} {'(%s)' % dat if dat else ''}. {tit}. {jou}. {'Pubmed: ' + pbm if pbm else ''}"

或者您可以简单地使用and 运算符:

return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}"

【讨论】:

  • 非常感谢。如果你想用'dat'键(=日期)做同样的事情怎么办?例如,如果json文件中缺少'dat'值,我不想打印括号()
【解决方案2】:

一个简单但略显笨拙的解决方法是在字符串中添加格式装饰。

try:
    pbm = ". Pubmed: " + art['pubmedId_s']
except (KeyError, NameError):
    pbm = ""
...
print(f"{nom} ({dat}). {tit}. {jou}{pbm}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2013-09-03
    相关资源
    最近更新 更多