簡體   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