2009-05-26 124 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