i found this code here and i tested the code and it isn't working for me

this is what my code looks like:

# PURPOSE: to count the number of words, lines, and characters in a file
#
# INPUT(S): a file name to be used
#
# OUTPUT(S): count for number of lines, words, and characters in the file
#
# EXAMPLES: input:  ; output:
#           input:  ; output:
#
################################################################################
import string

def fileCount():
    lineCount = 0
    wordCount = 0
    charCount = 0
    list = []
    
    fname = raw_input('Enter the name of the file to be used: ')
    infile = open(fname, 'r')

   
    for range in infile:
        lineCount = lineCount + 1
        list = string.split(readline, '')
        wordCount = wordCount + len(list)
        for ch in file:
            charCount = charCount + 1

            
    print "There are", lineCount, "lines in the file."
    print "There are", charCount, "characters in the file."
    print "There are", wordCount, "words in the file."

    infile.close()

fileCount()

im getting an error in the python shell and it is below.

list = string.split(line, '')
NameError: global name 'line' is not defined

since i found this code somewhere else and the thread is posted as solved im guessing that i did something wrong when i re-wrote it to test. any help is appreciated, thank you!

Dani AI

Generated

Nice catch on the swapped values, and +1 to for pointing out the shadowed names. The two big issues in the first snippet were (1) using different variable names than the ones you looped with (line vs range/readline/file), and (2) counting characters by iterating over words. That second one drops spaces and newlines, which is why your character count was too low. If you want a character count that includes spaces (optionally newlines), count from the original line string, not from split words. Also avoid names like list, file, or range for variables.

Here is a single-pass, streaming version that works on big files and in both Python 2 and 3. It counts lines, words, and characters; you can choose whether to include newlines in the character count.

import io

def file_count(path, include_newlines=False, encoding='utf-8'):
    lines = words = chars = 0
    # newline=None normalizes \r\n and \r to \n so subtraction below is correct
    with io.open(path, 'r', encoding=encoding, errors='replace', newline=None) as f:
        for line in f:
            lines += 1
            words += len(line.split())           # split on any whitespace
            if include_newlines:
                chars += len(line)               # includes the trailing '\n' if present
            else:
                chars += len(line) - (1 if line.endswith('\n') else 0)
    return lines, words, chars

Notes:

  • If you are on Python 3, replace raw_input with input and use print(); your function above is otherwise fine.
  • ’s read-all-at-once style is short and fine for small files; the version here avoids loading the entire file into memory.
  • As suggested, consider checking os.path.isfile(path) before opening, and be clear about what you want to count: do you include punctuation, tabs, or only letters? Adjust split() or use re.findall(r'\w+', line) if your definition of a “word” is different.

Recommended Answers

All 9 Replies

here is my updated code and it works fine but i had to delete the section that counted the characters because is was causing the error.

import string

def fileCount():
    lineCount = 0
    wordCount = 0
    charCount = 0
    mylist = []
    
    fname = raw_input('Enter the name of the file to be used: ')
    infile = open(fname, 'r')

    for line in infile:
        lineCount = lineCount + 1
        mylist = string.split(line, ' ')
        wordCount = wordCount + len(mylist)
   

    print "There are", lineCount, "lines in the file."
    print "There are", charCount, "characters in the file."
    print "There are", wordCount, "words in the file."

    infile.close()

fileCount()

so the code works fine except i need help with the character count section of my code. should i just write a new function to handle this?

Okay, first off... See all of those purple words now that it's in the [-code-] tags? Yeah, those mean that they are internally defined, and do something. You want to change all of those variables to something else.
Second, your error is self-explanatory, the variable "line" is not defined anywhere in the program.

Here's a good working program:

# PURPOSE: to count the number of words, lines, and characters in a file
#
# INPUT(S): a file name to be used
#
# OUTPUT(S): count for number of lines, words, and characters in the file
#
# EXAMPLES: input:  ; output:
#           input:  ; output:
#
################################################################################
def fileCount(f):
    # Define all variables required
    linecount = 0
    wordcount = 0
    charcount = 0
    words = []

    # Open the file
    _file = open(f, 'r')

    # Loop through each line
    for line in _file:
        linecount += 1
        word = line.split()
        words += word

    # Loop through all words found
    for word in words:
        wordcount += 1
        # Loop through each word for characters
        for char in word:
            charcount += 1

    return (linecount, wordcount, charcount)

# Name of the file
fname = raw_input('Enter the name of the file to be used: ')
# Unpack the tuple returned by the fileCount
lineCount, charCount, wordCount = fileCount(fname)
print "There are", lineCount, "lines in the file."
print "There are", charCount, "characters in the file."
print "There are", wordCount, "words in the file."

EDIT: Didn't notice your post when I quick posted xD

Okay, first off... See all of those purple words now that it's in the [-code-] tags? Yeah, those mean that they are internally defined, and do something. You want to change all of those variables to something else.
Second, your error is self-explanatory, the variable "line" is not defined anywhere in the program.

Here's a good working program:

# PURPOSE: to count the number of words, lines, and characters in a file
#
# INPUT(S): a file name to be used
#
# OUTPUT(S): count for number of lines, words, and characters in the file
#
# EXAMPLES: input:  ; output:
#           input:  ; output:
#
################################################################################
def fileCount(f):
    # Define all variables required
    linecount = 0
    wordcount = 0
    charcount = 0
    words = []

    # Open the file
    _file = open(f, 'r')

    # Loop through each line
    for line in _file:
        linecount += 1
        word = line.split()
        words += word

    # Loop through all words found
    for word in words:
        wordcount += 1
        # Loop through each word for characters
        for char in word:
            charcount += 1

    return (linecount, wordcount, charcount)

# Name of the file
fname = raw_input('Enter the name of the file to be used: ')
# Unpack the tuple returned by the fileCount
lineCount, charCount, wordCount = fileCount(fname)
print "There are", lineCount, "lines in the file."
print "There are", charCount, "characters in the file."
print "There are", wordCount, "words in the file."

EDIT: Didn't notice your post when I quick posted xD

i just tested your code and i think the character and word counts are in the opposite places.
this is what i got when i ran the program:
Enter the name of the file to be used: mywctext.txt
There are 4 lines in the file.
There are 14 characters in the file.
There are 42 words in the file.

this is what i should have gotten:
Enter the name of the file to be used: mywctext.txt
There are 4 lines in the file.
There are 42 characters in the file.
There are 14 words in the file.

lineCount, charCount, wordCount = fileCount(fname)print "There are", lineCount, "lines in the file."print "There are", charCount, "characters in the file."print "There are", wordCount, "words in the file."

i found the problem. charCount and wordCount need to be switched in that first line.

################################################################################
#
# created on:4/7/10
#
# by: Kristin Jock
#
# PURPOSE: to count the number of words, lines, and characters in a file
#
# INPUT(S): a file name to be used
#
# OUTPUT(S): count for number of lines, words, and characters in the file
#
# EXAMPLES: input: a file  ; output:
#           input: a file ; output:
#
################################################################################
import string

def fileCount(fname):
    #counting variables
    lineCount = 0
    wordCount = 0
    charCount = 0
    words = []
    
    #file is opened and assigned a variable
    infile = open(fname, 'r')
    
    #loop that finds the number of lines in the file
    for line in infile:
        lineCount = lineCount + 1
        word = line.split()
        words = words + word
        
    #loop that finds the number of words in the file
    for word in words:
        wordCount = wordCount + 1
        #loop that finds the number of characters in the file
        for char in word:
            charCount = charCount + 1
    #returns the variables so they can be called to the main function        
    return(lineCount, wordCount, charCount)
   

def main():
    fname = raw_input('Enter the name of the file to be used: ')
    lineCount, wordCount, charCount = fileCount(fname)

    print "There are", lineCount, "lines in the file."
    print "There are", charCount, "characters in the file."
    print "There are", wordCount, "words in the file."



main()

here is the final revision of my code

Your way is so complicated :

def fileCount(filename):
    txt=open(filename).read()
    linecount=len(txt.split("\n"))
    wordcount=len(txt.split())
    charcount=len(txt.replace("\n","")) # if you don't want tou count the '\n'
    return (linecount, wordcount, charcount)

If you would like to save your poor computer from overwork and get head ache from splitting ;). Instead put that energy for checking that file is there:

import os, sys
def fileCount(filename):
    """
    Error checking version of text statistics count.
    Returns the ready to print or put to label result.
    """
    if isinstance(filename, basestring) and os.path.isfile(filename):
        txt = open(filename).read()
        linecount = txt.count('\n')
        ## if you want textual result
        return """
    File %s has %i lines.
    It contains %i words and its' total length is %i letters (white space counted).
    """ % (filename,linecount,len(txt.split()),len(txt))

         ## if you want raw stats
##        return (filename,linecount,len(txt.split()),len(txt))
    else: print >>sys.stderr,'No file', filename

print fileCount(sys.argv[0])
print fileCount("surely_not_existing_file")
print fileCount(123)
print fileCount(None)

i'm a begginer python user so all this advanced code is just over my head.

If you found my example overcomplicated how about:

import os, sys

def fileCount(filename):
    """   simplistic version  of file counting   """
    ## let's see if this thing exists
    if  os.path.isfile(filename): 
        ## let's read all file as one string including the new lines at the end of line
        txt = open(filename).read()
        ## let's give the data as return value, first the object counted
        ## then the counts of it's structure from biggest to smallest
        return (filename,  ## what was counted
                txt.count('\n'), ## linecount by counting the end of line charactes
 ## word count by putting words to list and counting it's length,
 ##     drops any white space characters surrounding the words.
                len(txt.split()),
                len(txt)) ## letters 
    else: print 'No file', filename

## let's count this program code's own statistics as a test
print "%s has %i lines, %i words and %i letters." % fileCount(sys.argv[0])

Any clearer?

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.