2014-08-28 54 views
-4

如何统计每一行。读取一个文件并每行计数一次

def file_size(filename): 
    infile = open(filename) 
    for line in infile: 
     return (len(line)) 
    infile.close() 

我的代码只是计算第一行的致命词,我需要在整个文件名中计算总词数。

+6

你知道什么是'return'呢? – leon 2014-08-28 03:31:47

+2

你是什么意思“计数每一行”?你是说每条线的长度? – SethMMorton 2014-08-28 03:31:53

+1

你是否想要返回一个数字,即行数(或每行的长度总和),还是包含每行长度的列表? – SethMMorton 2014-08-28 03:33:43

回答

-2
>>> def file_size(filename): 
    infile = open(filename,'r') 
    count=0 
    total_line=0; 
    for line in infile: 
      total_line+=1 
      for i in line: 
        count+=1 
    infile.close() 
    return("Total Char = "+str(count) +" Total Lines = "+str(total_line)) 



>>> file_size("Cookie.py") 
'Total Char = 238 Total Lines = 5' 
+1

这不是一个好的答案,因为它会在函数返回后尝试关闭该文件,这会进一步误导/混淆OP。 – SethMMorton 2014-08-28 05:18:59

1

我会做这样的事情:

def file_size(filename): 
    with open(filename) as f: 
     return sum(len(_.split()) for _ in f.readlines()) 
+1

'...在f'中就足够了,你不需要'...在f.readlines()'这里。 – Matthias 2014-08-28 08:12:40

+0

而且'_'通常只在变量未被使用的情况下使用......您在此处使用它来获取该行的长度。 – SethMMorton 2014-08-28 14:12:31

1
def file_size(filename): 
    lines = [] 
    with open(filename) as infile: 
     total = 0 
     for line_num, line in enumerate(infile, 1): 
      print("The length of line", line_num, "is", len(line)) 
      lines.append(len(line)) 
      total += 1 
     print("There are a total of", total, "lines") 
    return lines, total 
+1

我认为OP想要从函数中返回总数。 – SethMMorton 2014-08-28 05:19:57

+0

@SethMMorton:OP的帖子中不太清楚,这就是为什么我回答两个问题,我认为OP可能要求 – inspectorG4dget 2014-08-28 21:18:36

+0

但是这个函数返回'None' ...我的意见是解决了这个事实,我认为OP要通知从他的功能返回* something *,而不是打印。 – SethMMorton 2014-08-28 21:28:13

相关问题