butterflyTee 0 Light Poster

Word Count. A Common Utility On Unix/linux Systems Is A Small Program Called "wc." This Program Analyzes A File To Determine The Number Of Lines, Words, And Characters Contained Therein. Write A Version Of Wc. The Program Should Accept A File Name As Input And Than Print Three Numbers Showing The Count Of Lines, Words, And Characters In The File. I use Gettysburg address.

#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

The posted snippet from is on the right track (counting characters and words), but it has a few practical problems worth calling out: a variable-name typo that prevents the line count from being computed, the file being opened/read more than once, files being closed twice, and no handling for missing files or large inputs. Also note the difference between "characters" (Unicode code points in text mode) and "bytes" (what GNU wc reports by default) — pick the one required by the assignment.

A compact, robust approach uses a single pass over the file, a context manager so the file is always closed, and a small state machine to count words correctly across chunk boundaries (important for large files). The example below is Python 3 and streams the file in 8 KB chunks so it scales:

#!/usr/bin/env python3
import sys

def wc(path):
    lines = words = chars = 0
    in_word = False
    with open(path, 'r', encoding='utf-8', errors='replace') as f:
        while True:
            chunk = f.read(8192)
            if not chunk:
                break
            chars += len(chunk)
            lines += chunk.count('\n')
            for ch in chunk:
                if ch.isspace():
                    in_word = False
                else:
                    if not in_word:
                        words += 1
                        in_word = True
    return lines, words, chars

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Usage: {} filename'.format(sys.argv[0]), file=sys.stderr)
        sys.exit(2)
    try:
        l, w, c = wc(sys.argv[1])
    except OSError as e:
        print('Error:', e, file=sys.stderr)
        sys.exit(1)
    print(f'{l} {w} {c}')

Notes and troubleshooting:

  • To emulate GNU wc's byte count, open the file in binary mode ('rb') and sum len(chunk) on byte chunks.
  • For small files a one-shot data = f.read() with data.split() works, but it uses more memory and can mis-handle encodings.
  • If running under Python 2, replace the sys.argv/print usage appropriately (prefer upgrading to Python 3).
  • The streaming approach avoids double reads and prevents off-by-one errors when a word is split across a chunk.
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.