使用pep8验证python语法时得到错误的输出

2024-06-25 23:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用pep8模块和flake8api验证python语法。为了验证,将创建一个字符串,其中包含要忽略的代码,稍后将在传递给函数以验证语法时转换为元组。你知道吗

ignore_code = """
        'E101','E111','E112','E113','E114','E115',
        'E116','E121','E122','E123','E124','E125',
        """.replace("\n",' ')

if flake8.main.check_file(fileName,ignore=tuple(ignore_code),complexity=-1):
    return False
else:
    return True

忽略8的关键字。main.check\u文件功能应该是

('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125',)

相反地

("'", 'E', '1', '0', '1', "'", ',', "'", 'E', '1', '1', '1', "'", ',', "'", 'E', '1', '1', '2', "'", ',', "'", 'E', '1', '1', '3', "'", ',', "'", 'E', '1', '1', '4', "'")

如何通过忽略'\n'和额外的空格将多行字符串转换为元组?你知道吗


Tags: 字符串语法code元组ignoree123e121e101
1条回答
网友
1楼 · 发布于 2024-06-25 23:30:51

你的问题是当你做tuple(ignore_code)这就是你传递的东西。你知道吗

>>> tuple(ignore_code)
(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "'", 'E', '1', '0', '1', "'", ',', "'", 'E', '1', '1', '1', "'", ',', "'", 'E', '1', '1', '2', "'", ',', "'", 'E', '1', '1', '3', "'", ',', "'", 'E', '1', '1', '4', "'", ',', "'", 'E', '1', '1', '5', "'", ',', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "'", 'E', '1', '1', '6', "'", ',', "'", 'E', '1', '2', '1', "'", ',', "'", 'E', '1', '2', '2', "'", ',', "'", 'E', '1', '2', '3', "'", ',', "'", 'E', '1', '2', '4', "'", ',', "'", 'E', '1', '2', '5', "'", ',', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ')

你基本上已经说了你需要做什么。你知道吗

ignore keyword of flake8.main.check_file function should be ('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125',)

你应该使ignore_code成为你想要传递的iterable,即

ignore_code = ('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125')
flake8.main.check_file(fileName, ignore=ignore_code, complexity=-1)

如果你想从多行字符串中得到想要的结果,你需要格式化它。执行.replace("\n", " ")不会削减它,因为其中的空格字符比换行符多,而且内部项用引号括起来。此外,tuple(some_iterable)生成iterable中项目的元组。字符串是其字符的iterable,但您希望iterable的项是'E101'之类的字符串,而不是字符。你知道吗

我能从下面得到你要找的元组。你知道吗

import ast
the_tuple = tuple([ast.literal_eval(item.strip()) for item in ignore_code.split(",") if item.strip()])
#the_tuple
#('E101', 'E111', 'E112', 'E113', 'E114', 'E115', 'E116', 'E121', 'E122', 'E123', 'E124', 'E125')

要详细说明该代码及其如何格式化多行字符串:

ignore_code.split(",")将字符串拆分为一个列表,列表项由该字符串中由,字符分隔(不包括)的部分组成。即["\n 'E101'", "'E111'",#etc]

到目前为止,这些项中仍然有空格。item.strip()将删除字符串中的前导和尾随空格字符,例如换行符、空格、制表符等

现在您就快到了,但是项目看起来像这样"'E101'", "'E111'",它们是包含文字'字符的字符串。要想以您想要的方式解释这些,您可以使用ast.literal_eval对字符串进行文本求值,它将"'E101'"求值为字符串'E101'

最后,有一个项是空字符串(由于字符串中的,),需要删除它。因此条件if item.split()被添加到表达式中。你知道吗

我们把这个想法放到一个生成器表达式[ast.literal_eval(item.strip()) for item in ignore_code.split(",") if item.strip()]中,在英语中,可以这样说

"Give me a list, whose items consist of ast.literal_eval(item.strip()) where item is every item from the list ignore_code.split(","), but only if the value of item.strip() is a non-empty string."

相关问题 更多 >