2009-05-26 123 views
1

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

回答

2

使用內置函數open()而不是codecs.open()

你觸犯非Unicode(Python的3 bytes,Python的2 str)和Unicode(Python 3的str,Python的2 unicode)字符串類型之間的區別的運行。 Python 3不會像Python 2那樣在非Unicode和Unicode之間自動轉換。使用codecs.open()而不使用encoding參數時,將返回一個對象,該對象在讀取該對象時產生bytes

此外,您countLOC功能將無法正常工作:

for letter in range(comment): 
    if not letter.whitespace: 
     LOC += 1 
     break    

,對於循環會遍歷數從零到一個小於'#'字符串(letter = 0, 1, 2...)中的位置; whitespace不是一個整數的方法,即使它是,你也沒有調用它。

此外,如果該行不包含#,則永遠不會增加LOC。

「固定」,但你countLOC否則忠實(和低效)版本:

def countLOC(inFile): 
    LOC = 0 
    for line in inFile: 
     if line.isspace(): 
      continue 
     comment = line.find('#') 
     if comment > 0: 
      for letter in line[:comment]: 
       if not letter.isspace(): 
        LOC += 1 
        break 
     else: 
      LOC += 1 
    return LOC 

我怎麼可能會寫功能:

def count_LOC(in_file): 
    loc = 0 
    for line in in_file: 
     line = line.lstrip() 
     if len(line) > 0 and not line.startswith('#'): 
      loc += 1 
    return loc 
+0

我發現我的錯誤與letter.whitespace,忘記使字母串的索引。而且我知道我沒有添加到LOC計數器,如果沒有找到'#',我只是沒有得到那麼遠,因爲以前的錯誤。感謝代碼,但我很難從C++寫出「pythonically」。 lstrip()中的問題 - 爲什麼使用它而不是strip()? – Justen 2009-05-26 05:25:15

1

你實際上傳遞一個打開的文件的功能?也許嘗試打印類型(文件)和類型(線),因爲這裏有什麼可疑的 - 以打開的文件作爲參數,我不能重現你的問題! (在你的代碼中有其他的錯誤,但沒有會導致這種異常的錯誤)。哦,順便說一句,作爲最佳做法,不要使用內置的名稱,如file,爲了您自己的目的 - 這會導致令人難以置信的混亂!

+0

好吧,我加滿源到我的職位和將參數名稱從'文件'更改爲'inFile',並且在嘗試type()命令後,類型(inFile)= type(line)= Am I將文件錯誤地傳遞給函數上? – Justen 2009-05-26 04:40:15