您如何更有效地列出关键字作为条件? [英] How do you list keywords as conditions more effectively?

查看:85
本文介绍了您如何更有效地列出关键字作为条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,该脚本会清理bibtex条目并将其保存到我的库文件中.我需要脚本读取.bib文件,然后将其内容写入库文件,但不包括某些字段/行.我已经尝试过将要排除的每个字段放入

I'm trying to write a script that cleans up and saves bibtex entries into my library-file. I need the script to read a .bib file and then write its content into the library file but excluding certain fields/lines. I've tried things like putting every field I want to exclude into

exclusions = ["exclusion1","exclusion2","exclusion3",..."exclusionN"]

然后像这样循环遍历

if [ex for ex in exclusion not in line]:
   ...code...

但是那没有用,所以最终我解决了这个问题

But that didnt work so eventually I settled with this

...
with open("newbib.bib", "a") as f1:
    for line in lines:
         if "abstract" not in line and "keywords" not in line and "issn" not in line and "ISSN" not in line and "url" not in line and "URL" not in line and "eprint" not in line and "publisher" not in line and "address" not in line and "number" not in line and "day" not in line and "month" not in line and "pages" not in line:
                            f1.writelines(line)
...

我在下面显示的if语句可以解决问题,但这是一种非常糟糕的方法,对吗?另外,不必为每个字段添加大写字母也很好.

The if statement that I'm showing below does the trick but its a damn bad way to do it, right? Also, it would be nice to not have to add capitalization for each field.

推荐答案

您可以使用内置的 any all 来检查是否可迭代元素中的任何元素或所有元素都适用.在您的情况下,这意味着遍历所有排除项并检查它们是否不在该行中:

You can use the any or all builtin to check whether any or all elements of an iterable apply. In your case, that means iterating through all exclusions and checking whether they are not in the line:

if all(ex not in line for ex in exclusion):
    ...

这篇关于您如何更有效地列出关键字作为条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆