我試圖測試一個/ t或空格字符,我不明白爲什麼這段代碼不起作用。我正在做的是讀取一個文件,計算文件的loc,然後記錄文件中每個函數的名字以及它們的代碼行。下面的代碼是我試圖爲函數計算loc的地方。str.startswith()沒有按照我的意圖工作
import re
...
else:
loc += 1
for line in infile:
line_t = line.lstrip()
if len(line_t) > 0 \
and not line_t.startswith('#') \
and not line_t.startswith('"""'):
if not line.startswith('\s'):
print ('line = ' + repr(line))
loc += 1
return (loc, name)
else:
loc += 1
elif line_t.startswith('"""'):
while True:
if line_t.rstrip().endswith('"""'):
break
line_t = infile.readline().rstrip()
return(loc,name)
輸出:
Enter the file name: test.txt
line = '\tloc = 0\n'
There were 19 lines of code in "test.txt"
Function names:
count_loc -- 2 lines of code
正如你看到的,我的測試打印的行顯示/噸,但如果聲明明確地說(或因此我認爲),它應該只執行不存在空白字符。
這裏是我完整的測試文件,我一直在使用:
def count_loc(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:
line = line.strip()
if len(line) > 0 \
and not line.startswith('//') \
and not line.startswith('/*'):
loc += 1
func_loc, func_name = checkForFunction(line);
elif line.startswith('/*'):
while True:
if line.endswith('*/'):
break
line = infile.readline().rstrip()
return loc
if __name__ == "__main__":
print ("Hi")
Function LOC = 15
File LOC = 19
不要發佈重複(http://stackoverflow.com/questions/929169/str-startswith-not-working-as-i-intended)。 – 2009-05-30 07:02:26