我正在嘗試使用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