0

What I would like the final code to execute is read a string of names in a text document named, 'names.txt'. Then tell the program to calculate how many names there are in that file and display the amount of names. The code I have so far was meant to display the sum of the numbers in a text file, but it was close enough to the program I need now that I think I may be able to rework it to gather the amount of strings/names and display that instead of the sum.

Here is the code so far:

def main():
    #initialize an accumulator.
    total = 0.0

    try:
        # Open the file.
        myfile = open('names.txt', 'r')

        # Read and display the file's contents.
        for line in myfile:
            amount = float(line)
            total += amount

        # Close the file.
        myfile.close()

    except IOError:
        print('An error occured trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file.')

    except:
        print('An error occured.')

# Call the main function.
main()

I am still really new to Python programming so please don't be too harsh on me. If anyone can figure out how to rework this to display the amount of numbers/names instead of the sum of numbers. I would greatly appreciate it. If this program cannot be reworked, I would be happy to settle for a new solution.

Edit: This it an example of what the 'names.txt' will look like:

john

mary

paul

ann

Ken White
  • 123,280
  • 14
  • 225
  • 444
Alex Kiss
  • 11
  • 3
  • 8
  • 1
    Are the names each on different lines? – Waleed Khan Jul 18 '12 at 16:51
  • Is this a homework assignment? Also, how are the names delimited? Is each on its own line, are they separated by semicolons? Commas? Not enough info to answer this really. – Silas Ray Jul 18 '12 at 16:51
  • can you show us an example of the names.txt file? Is the format of that file always the same (e.g. is every name on a new line or are they comma separated or space separated etc)? – ntlarson Jul 18 '12 at 16:51
  • 4
    So what have you tried changing to make it work with names and counts? Try changing it and making it work, and then come back here with specific questions about your new code and what's not working. – Ken White Jul 18 '12 at 16:52
  • 1
    +1 to @arxanas. Also, are you trying to count the number of names in the file, or the number of unique names in the file. If it's 1 name per line, you're better off using `wc -l names.txt` or `sort -u names.txt | wc -l` – inspectorG4dget Jul 18 '12 at 16:52
  • 1
    @inspectorG4dget It's [tag:homework], that's not allowed. – Waleed Khan Jul 18 '12 at 16:54
  • looks like http://projecteuler.net/problem=22 to me and if so, @Alex Kiss really needs to read the second paragraph of the problem as he's not addressing it at all (hint: `ord()`) – msw Jul 18 '12 at 16:59
  • possible duplicate of [Project Euler #22 Python, 2205 points missing?](http://stackoverflow.com/questions/10493702/project-euler-22-python-2205-points-missing) – msw Jul 18 '12 at 17:04
  • if it is that he is missing a whole lot... – Joran Beasley Jul 18 '12 at 17:05

5 Answers5

0
fh = open("file","r")
print "%d lines"%len(fh.readlines())
fh.close()

or you could do

 fh=open("file","r")
 print "%d words"%len(fh.read().split())
 fh.close()

All this is readily available information that is not hard to find if you put forth some effort...just getting the answers usually results in flunked classes...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Considering the names in your text files are delimited by line.

myfile = open('names.txt', 'r')
lstLines = myfile.read().split('\n')

dict((name,lstLines.count(name)) for name in lstLines)

This creates a dictionary of each name having its number of occurrence.

To search for the occurrence of perticular name such as 'name1' in the list

lstLines.count('name1')
Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26
0

Assuming names are splitted using whitespaces :

def main():
    #initialize an accumulator.
    total = 0.0

    try:
        # Open the file.
        myfile = open('names.txt', 'r')

        # Read and display the file's contents.
        for line in myfile:
            words = line.split()
            total += len(words)

        # Close the file.
        myfile.close()

    except IOError:
        print('An error occured trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file.')

    except:
        print('An error occured.')

# Call the main function.
main()
Nicolas Barbey
  • 6,639
  • 4
  • 28
  • 34
0

If you just want to count the lines in the file

# Open the file.
myfile = open('names.txt', 'r')

#Count the lines in the file
totalLines = len(myfile.readlines()):

# Close the file.
myfile.close()
Mark Unsworth
  • 3,027
  • 2
  • 20
  • 21
  • 1. You could use `chunk.count('\n')` instead of `.readlines()` to count number of lines in a file, see [`wc-l.py` in the comments](http://stackoverflow.com/q/9371238/4279). 2. To count lines that match some condition, you could use a generator: [`sum(1 for line in myfile if match(line))`](http://stackoverflow.com/a/11546679/4279) without loading the whole file in memory as `.readlines()` does. – jfs Apr 29 '14 at 06:12
-1

Use with statement to open a file. It will close the file properly even if an exception occurred. You can omit the file mode, it is default.

If each name is on its own line and there are no duplicates:

with open('names.txt') as f:
    number_of_nonblank_lines = sum(1 for line in f if line.strip())
name_count = number_of_nonblank_lines

The task is very simple. Start with a new code to avoid accumulating unused/invalid for the problem code.

If all you need is to count lines in a file (like wc -l command) then you could use .count('\n') method:

#!/usr/bin/env python
import sys
from functools import partial

read_chunk = partial(sys.stdin.read, 1 << 15) # or any text file instead of stdin
print(sum(chunk.count('\n') for chunk in iter(read_chunk, '')))

See also, Why is reading lines from stdin much slower in C++ than Python?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670