:?:

#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()

Dani AI

Generated

A few practical notes and a compact, more robust pattern to complement 's original attempt and 's fixes.

The original code had two common issues to watch for: a variable-name mismatch when counting lines (assigning to one name and calling len(...) on another) and redundant file closes. Also, loading the entire file with read() is fine for small files but will use a lot of memory on large inputs. Decide up front whether "characters" should include newline characters and whether "words" means whitespace-separated tokens or language-aware word tokens — that affects the technique.

A memory-efficient single-pass approach (Python 3) reads the file line by line, updates counters, and avoids keeping the whole file in memory. It also handles encoding errors gracefully:

# Python 3 — single-pass, memory-efficient
import re

filename = input("Enter file path: ")
lines = words = chars = 0
word_re = re.compile(r"\w+")

with open(filename, 'r', encoding='utf-8', errors='replace') as f:
    for line in f:
        lines += 1
        chars += len(line)               # includes newline characters
        words += len(word_re.findall(line))

print(lines, words, chars, filename)

Quick alternatives and troubleshooting:

  • For a simple whitespace-based word count, use len(line.split()) instead of regex.
  • To count lines quickly: sum(1 for _ in f).
  • To count bytes instead of characters (avoid encoding issues): open in binary mode rb and sum len(chunk) over reads.
  • Wrap file opening in try/except to handle missing files and permission errors.
  • Verify expected results against the Unix wc tool if available, and be explicit about whether newlines and punctuation should be counted.

These points build on 's streamlining while avoiding loading the entire file and giving clearer control over encoding and token definition.

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.