检查列表中是否存在至少一个字符串 - python

我有代码检查我的word_list中是否至少有一个情态动词。

with open('Requirements_good.txt') as myfile:
    word_list=[word for line in myfile for word in line.split()]


with open('Badwords_modalverbs.txt') as file:
    modalv = 0
    for word in file.readlines():
        if word.strip() in word_list:
            modalv = 1
    if modalv == 1:
        print ("one of the words found")

但是必须有一种更简单,更优雅的方法来解决此问题。什么是最快的检查方法?

以及如何检查对立面:如果找不到任何单词,则打印任何内容

参考方案

首先,将word_list设置为集合而不是列表,以便高效地测试其成员资格。然后,您可以使用any函数:

with open('Requirements_good.txt') as myfile:
    # set comprehension instead of list comprehension
    word_set = {word for line in myfile for word in line.split()}

with open('Badwords_modalverbs.txt') as file:
    if any(word.strip() in word_set for word in file):
        print("one of the words found")

这样比较有效,因为您不再搜索列表来测试成员资格,而且any函数在找到一个匹配项后也不会继续搜索。在这里file.readlines()函数也是不必要的; for word in file遍历行而不先创建列表。

python-docx应该在空单元格已满时返回空单元格 - python

我试图遍历文档中的所有表并从中提取文本。作为中间步骤,我只是尝试将文本打印到控制台。我在类似的帖子中已经看过scanny提供的其他代码,但是由于某种原因,它并没有提供我正在解析的文档的预期输出可以在https://www.ontario.ca/laws/regulation/140300中找到该文档from docx import Document from…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…