我正在尝试使用str.find(),它不断提出错误,我做错了什么?str.find遇到问题()
import codecs
def countLOC(inFile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
LOC = 0
for line in inFile:
if line.isspace():
continue
comment = line.find('#')
if comment > 0:
for letter in range(comment):
if not letter.whitespace:
LOC += 1
break
return LOC
if __name__ == "__main__":
while True:
file_loc = input("Enter the file name: ").strip()
try:
source = codecs.open(file_loc)
except:
print ("**Invalid filename**")
else:
break
LOC_count = countLOC(source)
print ("\nThere were {0} lines of code in {1}".format(LOC_count,source.name))
错误
File "C:\Users\Justen-san\Documents\Eclipse Workspace\countLOC\src\root\nested\linesOfCode.py", line 12, in countLOC
comment = line.find('#')
TypeError: expected an object with the buffer interface
我发现我的错误与letter.whitespace,忘记使字母串的索引。而且我知道我没有添加到LOC计数器,如果没有找到'#',我只是没有得到那么远,因为以前的错误。感谢代码,但我很难从C++写出“pythonically”。 lstrip()中的问题 - 为什么使用它而不是strip()? – Justen 2009-05-26 05:25:15