:?:

#The number of lines, and the number of words.


import string


def main():
data = raw_input("Enter the path and name of your ")
infile = file(data, 'r')
data_file = infile.read()
number_of_characters = len(data_file)
print "The number of characters in your text is", number_of_characters

list_of_words = string.split(data_file)
number_of_words = len(list_of_words)
print "The number of words in your text is", number_of_words
infile.close()

secondfile = file(data, 'r')
line_of_text = secondfile.readlines()
print line_of_text
number_of_lines = len(lines_of_text)
print "The number of lines in your text is" , number_of_lines

infile.close()

main()

Recommended Answers

All 2 Replies

You are making progress on your own. Just some small corrections and it does work. From here you can improve the code.

#The number of lines, and the number of words.

#import string  # not needed

def main():
    data = raw_input("Enter the path and name of your text file: ")
    
    infile = file(data, 'r')
    data_file = infile.read()
    infile.close()
    
    number_of_characters = len(data_file)
    print "The number of characters in your text is", number_of_characters
    
    list_of_words = data_file.split()
    number_of_words = len(list_of_words)
    print "The number of words in your text is", number_of_words
    
    secondfile = file(data, 'r')
    line_of_text = secondfile.readlines()
    secondfile.close()
    print line_of_text
    number_of_lines = len(line_of_text)
    print "The number of lines in your text is" , number_of_lines


main()

A somewhat more streamlined version with a properly formatted output ...

# The number of lines, words and characters in a text file.

def main():
    filename = raw_input("Enter the path and name of your text file: ")
    
    infile = file(filename, 'r')
    lines_of_text = infile.readlines()
    infile.close()
    
    number_of_lines = len(lines_of_text)
    
    # join list of lines to form one string
    str1 = ''.join(lines_of_text)
    number_of_characters = len(str1)
    
    # split string into a list of words
    list_of_words = str1.split()
    number_of_words = len(list_of_words)
    
    # show the result
    print "%d %d %d %s" % (number_of_lines, number_of_words, number_of_characters, filename)


main()

thank you, that was a big help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.