Python 基于文件最长行的输出特征
我想编写一个程序文件_stats.py,当在命令行上运行时,它接受一个文本文件名作为参数,并输出文件中字符数、单词数、行数和最长行的长度(以字符为单位)。如果我希望输出如下所示,是否有人知道这样做的正确语法:Python 基于文件最长行的输出特征,python,python-3.x,Python,Python 3.x,我想编写一个程序文件_stats.py,当在命令行上运行时,它接受一个文本文件名作为参数,并输出文件中字符数、单词数、行数和最长行的长度(以字符为单位)。如果我希望输出如下所示,是否有人知道这样做的正确语法: Characters: 553 Words: 81 Lines: 21 Longest line: 38 假设您的文件路径是一个字符串,类似这样的东西应该可以工作 file = "pathtofile.txt" with open(file, "r") as f: text =
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)
你只是在寻找如何找到最长的一行,还是所有这些值?关于如何找到这些值的解释。要按我上面的格式打印,我该怎么做?@user10200421我不会为你写所有代码,但我可以帮你。其他三个要容易得多。我已将文本拆分为行,因此您可以计算
len(行)
的行数。对于单词和字符,您需要执行另一个For循环。循环遍历每一行并.split(“”
)以除以空格。将每个列表的长度加在一起表示单词总数。字母也是一样,但你可以做len(word)
并把它们加起来。