Python是一个计算文件中的行和字符的函数

时间:2015-04-07 21:50:04

标签: python function count

有人可以看看我到目前为止做了些什么吗?我自己还没有成功找到问题。

def txt_file(file1):
    file1 = open('text.txt', 'r')
    linecount = 0
    charcount = 0
    for line in file1:
        linecount +=1
        for char in line:
            charcount += 1
    print "file1 contains", linecount, "lines and", charcount, "characters."
    file1.close()

4 个答案:

答案 0 :(得分:4)

这种方式更容易:

with open('text.txt') as the_file:
     data = [len(i) for i in the_file]
     line, char = len(data), sum(data)

答案 1 :(得分:1)

您的代码中存在多个错误:

  • 缩进
  • print必须在行循环之外
  • 您声明了一个您实际上不使用
  • 的函数参数

试试这段代码:

file1 = open('textfile.txt', 'r')
linecount = 0
charcount = 0
for line in file1:
    linecount +=1
    for char in line:
        charcount += 1
print ("file1 contains", linecount, "lines and", charcount, "characters.")
file1.close()

如果你需要一个函数定义并以这种方式调用它:

def txt_file():
    file1 = open('textfile.txt', 'r')
    linecount = 0
    charcount = 0
    for line in file1:
        linecount +=1
        for char in line:
            charcount += 1
    print ("file1 contains", linecount, "lines and", charcount, "characters.")
    file1.close()
if __name__ == "__main__":
    txt_file()

在包含以下三行的示例文件中:

First Line
Second Line
Third Line

它产生以下输出:

file1 contains 3 lines and 33 characters.

(它还包括空格和换行符)

答案 2 :(得分:0)

当您使用for循环时:

for line in file1:
    line += 1

for循环中的变量line正是调用迭代的变量,与您正在寻找的内容无关。相反,在做了一些研究后,试试这个行:

linecount = open(file1).read().count('\n')

对于字符,使用for循环排除空格:

for i in file1:
    if i != " ":
        charcount += 1

答案 3 :(得分:0)

问题是print语句过多缩进。它是每个for循环执行的,需要移到最后。

更好的方法是使用len

file1=open("foo.txt", "r").readlines()

linecount=len(x)
charcount=sum(map(len, x))

print "file1 contains {0} lines and {1} characters".format(linecount, charcount)

charcount有效,因为它取每行的len然后对它们求和。