根据文件的最长行输出文件特征

时间:2018-08-12 01:20:20

标签: python python-3.x

我想编写一个程序file_stats.py,该程序在命令行上运行时接受文本文件名作为参数,并输出字符,单词,行数和最长行的长度(以字符为单位)在文件中。如果我希望输出看起来像这样,是否有人知道执行这样的正确语法:

Characters: 553
Words: 81
Lines: 21
Longest line: 38

2 个答案:

答案 0 :(得分:0)

假设您的文件路径是字符串,则类似这样的事情应该起作用

file = "pathtofile.txt"

with open(file, "r") as f:
    text = f.read()
    lines = text.split("\n")
    longest_line = 0
    for l in lines:
        if len(l) > longest_line:
            longest_line = len(l)
print("Longest line: {}".format(longest_line))

答案 1 :(得分:0)

整个程序

n_chars = 0
n_words = 0
n_lines = 0
longest_line = 0

with open('my_text_file') as f:
    lines = f.readlines()
    # Find the number of Lines
    n_lines = len(lines)
    # Find the Longest line
    longest_line = max([len(line) for line in lines])
    # Find the number of Words
    words = []
    line_words = [line.split() for line in lines]
    for line in line_words:
        for word in line:
            words.append(word)
    n_words = len(words)
    # Find the number of Characters
    chars = []
    line_chars = [list(word) for word in words]
    for line in line_chars:
        for char in line:
            chars.append(char)
    n_chars = len(chars)

print("Characters: ", n_chars)
print("Words: ", n_words)
print("Lines: ", n_lines)
print("Longest: ", longest_line)