Output features of a file based on its longest line
Clash Royale CLAN TAG#URR8PPP
Output features of a file based on its longest line
I want to write a program file_stats.py that when run on the command line, accepts a text file name as an argument and outputs the number of characters, words, lines, and the length (in characters) of the longest line in the file. Does anyone know the proper syntax to do something like this if I want the output to look like this:
Characters: 553
Words: 81
Lines: 21
Longest line: 38
An explainer on how to find the values.
– user10200421
Aug 12 at 1:34
2 Answers
2
Assuming your file path is a string, something like this should work
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))
To print in the format I had above, how would I do so?
– user10200421
Aug 12 at 1:33
@user10200421 I won't write all the code for you, but I can help you. The other three are a lot easier. I've split the text into lines, so you can count
len(lines)
for the number of lines. For words and characters you need to do another for loop. Loop through each line and .split(" ")
to divide by spaces. Add the length of each list together for total words. Same thing for letters but you can do len(word)
and add those up.– The Tesseract's Shadow
Aug 12 at 1:37
len(lines)
.split(" ")
len(word)
The whole program
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)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Are you just looking for how to find the longest line, or all of those values?
– The Tesseract's Shadow
Aug 12 at 1:21