【问题标题】:How do find out how many lines, words, and characters in a file?如何找出文件中有多少行、多少字和多少个字符?
【发布时间】:2019-08-28 15:13:41
【问题描述】:

我想编写一个函数,它返回整数的三元组“(a,b,c)”,其中 a 是文件中的行数,b 是文件中的字数,c 是文件中的字符数。

我是文件新手,不知道该怎么做。这是文件包含的内容,以防您无法查看:

是时候离开了,因为游泳池里已经挤满了掉进水里的鸟和动物:有一只鸭子和一只渡渡鸟, 一只鹦鹉和一只小鹰,以及其他一些好奇的生物。爱丽丝带领 一路上,一行人游到了岸边。

def get_data(filename):
    '''get_data(filename) -> (int,int,int)
    returns (# of lines,# of words,# of chars) in filename'''
    inFile = open('alice.txt', 'r')
    text = inFile.read()

    lines = len(filename.split('.'))
    words = len(filename.split(' '))
    chars = len(filename)

    return lines, words, chars

print(get_data('alice.txt'))
# should print (4, 52, 262)

在我的示例中,它应该打印 4、52 和 262 -- 实际上有 4 行。

【问题讨论】:

    标签: python-3.x file


    【解决方案1】:

    读取文件:

    f = open("../data/alice.txt", "r")
    txt = f.read()
    

    获取句子数量:

    len(txt.split('.'))
    3
    

    获取字数:

    len(txt.split(' '))
    52
    

    获取字符数:

    len(txt)
    261
    

    我将把剩下的功能留给你。

    【讨论】:

    • 我用上面的代码写了一个函数,但是我的输出是 (2, 1, 9) 而不是 (4, 52, 262)。
    • 是的,我看到原来的答案有错字,我已经修正了。
    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多