我的Python怎么了?

2024-10-01 19:25:34 发布

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

我编写了这个脚本来帮助我在特定文件中执行搜索。它的功能类似于grep,但是我需要比grep提供的更具体的东西,所以我正在尝试Python。在

我有一个类有三个方法。第二个方法listOccurrencesOfToDoInFile(第30行)失败。这是一个小脚本,但是由于标签在Python中很重要,所以我把它放在a gist, here中。有人能告诉我为什么我的貌似有效的Python是无效的吗?在

import os
import keyword
import sys


class Toodles:

    def walkAndList(directory):
        for dirname, dirnames, filenames in os.walk(directory):

            # print path to all filenames.
            for filename in filenames:
                workingFilename = os.path.join(dirname, filename)
                if(isSourceFile(filename)):
                    listOccurrencesOfToDoInFile(filename)

            # Advanced usage:
            # editing the 'dirnames' list will stop os.walk() from recursing into there.
            if '.git' in dirnames:
                # don't go into any .git directories.
                dirnames.remove('.git')

            for dirs in dirnames:
                self.walkAndList(os.path.join(dirname, dirs)


    #   Find occurences of "todo" and "fixme" in a file
    #   If we find such an occurence, print the filename, 
    #   the line number, and the line itself.
    def listOccurrencesOfToDoInFile(aFileName):
        input = open(aFileName)
        currentLine = 1
        for (line in input):
            line = line.lower()
            currentLine = currentLine + 1
            needle = "todo"
            if (needle in line):
                sys.stdout.write(aFileName + " (" + str(currentLine) + ")" + line)

    #Todo: add a comment
    def isSourceFile(self, name):
        fileName, fileExtension = os.path.splitext(name)
        if (".m" in fileExtension or ".c" in fileExtension or ".h" in fileExtension):
            return True
        return False


if ( __name__ == "__main__") {
    a = Toodles()
    a.walkAndList('.')
}   

Tags: thepathinimportforifosdef
1条回答
网友
1楼 · 发布于 2024-10-01 19:25:34

您错过了右括号:

 self.walkAndList(os.path.join(dirname, dirs)

请注意,有两个开口,但只有一个闭合帕伦斯。在

下一个问题是,您正在使用大括号进一步向下:

^{pr2}$

这是Python,而不是C、Java或Javascript;去掉大括号并使用冒号:

if __name__ == "__main__":
    a = Toodles()
    a.walkAndList('.')

那么您在for语句中使用括号的方式是不合法的Python:

for (line in input):

删除这些括号:

for line in input:

下一个问题是您没有为您的两个方法定义self

def walkAndList(directory):

以及

def listOccurrencesOfToDoInFile(aFileName):

添加self作为第一个参数:

def walkAndList(self, directory):
# ...
def listOccurrencesOfToDoInFile(self, aFileName):

接下来,您将Toodles.isSourceFile()Toodles.listOccurrencesOfToDoInFile()方法视为全局变量,您需要在这些方法前面添加self.,将它们作为当前实例上的方法调用:

if(isSourceFile(filename)):
    listOccurrencesOfToDoInFile(filename)

应为(无多余括号):

if self.isSourceFile(filename):
    self.listOccurrencesOfToDoInFile(filename)

然后在您想要的地方引用filename(缺少路径),取而代之的是workingFilename(其中包括路径):

self.listOccurrencesOfToDoInFile(workingFilename)

否则打开这些文件时会出错。在

那么,您的文件扩展名测试是有缺陷的;只需使用.endswith()来防止匹配文件,例如.csh或{}。而且,不需要首先要求if来测试某个东西是否是True,然后分别返回True或{};您可以直接返回布尔测试

def isSourceFile(self, name):
    return name.endswith(('.m', '.c', '.h'))

当循环遍历序列时,使用enumerate()函数为您生成计数器:

for currentLine, line in enumerate(input, 1):
    line = line.lower()

从1开始计算行数。在

注意,os.walk()已经为您遍历子目录。不必再重复了。通过删除以下行来删除递归:

for dirs in dirnames:
    self.walkAndList(os.path.join(dirname, dirs))

再做一些改进(使用with再次关闭打开的文件,设置needle外部循环,提前过滤,使用字符串格式,写出原始行,而不是小写),整个脚本变成:

import os
import sys


class Toodles(object):
    def walkAndList(self, directory):
        for dirname, dirnames, filenames in os.walk(directory):
            for filename in filenames:
                if self.isSourceFile(filename):
                    workingFilename = os.path.join(dirname, filename)
                    self.listOccurrencesOfToDoInFile(workingFilename)

            # Advanced usage:
            # editing the 'dirnames' list will stop os.walk() from recursing into there.
            if '.git' in dirnames:
                # don't go into any .git directories.
                dirnames.remove('.git')

    #   Find occurences of "todo" and "fixme" in a file
    #   If we find such an occurence, print the filename,
    #   the line number, and the line itself.
    def listOccurrencesOfToDoInFile(self, aFileName):
        needle = "todo"
        with open(aFileName) as input:
            for currentLine, line in enumerate(input, 1):
                if needle in line.lower():
                    sys.stdout.write('{}: ({}){}'.format(aFileName, currentLine, line))

    #Todo: add a comment
    def isSourceFile(self, name):
        return name.endswith(('.m', '.c', '.h'))


if __name__ == "__main__":
    a = Toodles()
    a.walkAndList('.')

相关问题 更多 >

    热门问题