我能在Python中的隐式字符串连接上获取一个Lint错误吗?

2024-04-16 18:46:20 发布

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

有没有什么方法可以在字符串的字面列表中得到丢失的逗号的lint错误?在

示例:

exceptions = ["banana", "pineapple", "apple"
              "pen"]

你可能认为这张单子上有4项,但说实话吧!”“苹果”和“笔”连成“applepen”。在

我害怕这些省略的逗号。有没有一些皮棉工具可以帮我找到它们?在

例2:

^{pr2}$

Tags: 方法字符串苹果示例apple列表错误exceptions
2条回答

我不知道你在使用什么样的源代码分析工具,所以我只能提出一个建议。但是,评论太长了,所以我写了一个概念验证脚本。在

其思想是使用Python的tokenize模块查看源代码,该模块从Python表达式生成标记。如果格式良好的Python代码包含隐式连续的字符串文本,它将显示为STRING标记,后跟NL。在

例如,让我们使用下面的源文件source.py作为测试用例。在

x = ("a"
        "b"  # some trailing spaces
# Coment line
"c"
""
     # The following is an explicit continuation
  "d" \
     "e")

在文件上运行python check.py < source.py命令将生成:

^{pr2}$

程序check.py只是概念证明,它不检查语法错误或其他边缘情况:

import sys
import tokenize


LOOKNEXT = False
tok_gen = tokenize.generate_tokens(sys.stdin.readline)
for tok, tok_str, start, end, line_text in tok_gen:
    if tok == tokenize.STRING:
        LOOKNEXT = True
        continue
    if LOOKNEXT and (tok == tokenize.NL):
            warn_header = "%d:%d: implicit continuation: " % start
            print >> sys.stderr, warn_header
            print >> sys.stderr, line_text
            indents = start[1] - 3
            if indents >= 0:
                print >> sys.stderr, "%s~~~^" % (" " * indents)
            else:
                print >> sys.stderr, "%s^" % (" " * start[1])
    LOOKNEXT = False

希望这个想法可以帮助您扩展lint工具或IDE。在

sublimitext3和pluginflake8(它是其他python lint插件的包装器)可以修复它。在

否则,您可以在一行中创建一个count((number of“)/2)-1和逗号的脚本,如果结果不匹配,则添加coma。在

编辑:

解释我的意思:

    def countQuotes(string):
        return string.count('"')
    def countCommas(string):
        return string.count(',')
    files = os.listdir('your/directory')
    for filename in files:
    if filename.endswith(".py"):
        with fileinput.FileInput("your/directory"+"/"+filename, inplace=True, backup='.bak') as fileContent:
        for line in fileContent:
            if '"' in line:
                numQuotes = countQuotes(line)
                numCommas = countCommas(line)
                if(numQuotes == 2 and ']' in line):
                    if(numCommas != 0):
                        #error, must delete a comma in right place and print line
                    else:
                        print(line)
                if(numQuotes == 2 and ']' not in line):
                    if(numCommas != 1):
                        #error, must add a comma in right place and print line
                    else:
                        print(line)
                if(numQuotes > 2):
                    if(numCommas > (numQuotes//2)-1)
                        #error, must delete a comma in right place and print line
                    elif(numCommas < (numQuotes//2)-1)
                        #error, must add a comma in right place and print line
                    else:
                        print(line)
           else:
                print(line)

这个方法必须有效,只要想一想,你必须在哪里插入或删除逗号,最终得到你想要的格式。在

相关问题 更多 >