繁体   English   中英

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

[英]Output features of a file based on its longest line

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

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

假设您的文件路径是一个字符串,则应该可以执行以下操作

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))

整个程序

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM