我编写了这个脚本来帮助我在特定文件中执行搜索。它的功能类似于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('.')
}
您错过了右括号:
请注意,有两个开口,但只有一个闭合帕伦斯。在
下一个问题是,您正在使用大括号进一步向下:
^{pr2}$这是Python,而不是C、Java或Javascript;去掉大括号并使用冒号:
那么您在
for
语句中使用括号的方式是不合法的Python:删除这些括号:
下一个问题是您没有为您的两个方法定义
self
:以及
添加
self
作为第一个参数:接下来,您将
Toodles.isSourceFile()
和Toodles.listOccurrencesOfToDoInFile()
方法视为全局变量,您需要在这些方法前面添加self.
,将它们作为当前实例上的方法调用:应为(无多余括号):
然后在您想要的地方引用
filename
(缺少路径),取而代之的是workingFilename
(其中包括路径):否则打开这些文件时会出错。在
那么,您的文件扩展名测试是有缺陷的;只需使用}。而且,不需要首先要求};您可以直接返回布尔测试:
.endswith()
来防止匹配文件,例如.csh
或{if
来测试某个东西是否是True
,然后分别返回True
或{当循环遍历序列时,使用
enumerate()
函数为您生成计数器:从1开始计算行数。在
注意,
os.walk()
已经为您遍历子目录。不必再重复了。通过删除以下行来删除递归:再做一些改进(使用
with
再次关闭打开的文件,设置needle
外部循环,提前过滤,使用字符串格式,写出原始行,而不是小写),整个脚本变成:相关问题 更多 >
编程相关推荐