Write a program that reads in the name of a file and prints out the number of ch
ID: 3565956 • Letter: W
Question
Write a program that reads in the name of a file and prints out the number of characters, words, and lines in the document. Include the end-of-line character in the number of characters. A word is any sequence of characters that is delineated by a space or end-of-line character.
Suppose the file td.txt contains the following data. There is no end-of-line character in the fourth line.
abcd efgh ijkl
mn op qrst uv
wx y z 0 1 23
45 67 89
The program works as follows:
Enter document name: td.txt
4 16 51
here is what i have so far. can somebody help me?
i hould point out i need to use loops and accumulators
def main():
num_lines = 0
num_words = 0
num_chars = 0
myfile=input("Enter document name: ")
myfile = "D:/td.txt"
myfile=open(myfile, 'r')
for line in myfile:
words = line.split()
num_lines = num_lines + 1
num_words = num_words + len(words)
num_chars = len(words)+ 1
print(num_chars, num_words, num_lines)
main()
Explanation / Answer
#!/bin/bash # Cleanup, version 3 # Warning: # ------- # This script uses quite a number of features that will be explained #+ later on. # By the time you've finished the first half of the book, #+ there should be nothing mysterious about it. LOG_DIR=/var/log ROOT_UID=0 # Only users with $UID 0 have root privileges. LINES=50 # Default number of lines saved. E_XCD=86 # Can't change directory? E_NOTROOT=87 # Non-root exit error. # Run as root, of course. if [ "$UID" -ne "$ROOT_UID" ] then echo "Must be root to run this script." exit $E_NOTROOT fi if [ -n "$1" ] # Test whether command-line argument is present (non-empty). then lines=$1 else lines=$LINES # Default, if not specified on command-line. fi # Stephane Chazelas suggests the following, #+ as a better way of checking command-line arguments, #+ but this is still a bit advanced for this stage of the tutorial. # # E_WRONGARGS=85 # Non-numerical argument (bad argument format). # # case "$1" in # "" ) lines=50;; # *[!0-9]*) echo "Usage: `basename $0` lines-to-cleanup"; # exit $E_WRONGARGS;; # * ) lines=$1;; # esac # #* Skip ahead to "Loops" chapter to decipher all this. cd $LOG_DIR if [ `pwd` != "$LOG_DIR" ] # or if [ "$PWD" != "$LOG_DIR" ] # Not in /var/log? then echo "Can't change to $LOG_DIR." exit $E_XCD fi # Doublecheck if in right directory before messing with log file. # Far more efficient is: # # cd /var/log || { # echo "Cannot change to necessary directory." >&2 # exit $E_XCD; # }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.