-2

The program must use a list of length 10 to count the occurrences of the 10 digits 0-9.

It should print like this:

I am not sure how to get it to add up the occurrences of each number every time it reads a line. Or how to get the totals into a list.

Number of 0's:      5
Number of 1's:      8
Number of 2's:     17

def main():
    intro()
    inFile = getFile()
    file, outfile = convertName(inFile)
    count, counts = countLines(file, outfile)
    printResults(count, counts)

def intro():
    print()
    print("Program to count letters in each line")
    print("in a file.")
    print("You will enter the name of a file.")
    print("The program will create an output file.")
    print("Written by --------.")
    print()
def getFile():
    inFile = input("Enter the name of input file: ")
    return inFile
def convertName(inFile):
    file = open(inFile, "r")
    outfile = (inFile.replace(".txt", ".out"))
    return file, outfile
def countLines(file, outfile):
    outfile = open(outfile, "w")
    count = 0
    num = 0
    numcount1 = []
    numcount = []
    for line in file:
        spl = line.split(" ")
        listx = list(spl)
        counts = {}
        for i in range(0, 10):
            count[i] = count[i, 0] + str(listx.count(i))
        for spl in line:

            if spl.isalnum():
                num = num + 1
            else:
                num = num + 0

        pr = str(num)+":        "+line+"\n"
        outfile.write(pr)
        count = count + 1
    return count, counts
def printResults(count, counts):
    print(count, counts)
main()
user3015970
  • 99
  • 1
  • 1
  • 6
  • 1
    Do you mind sharing with us, what the problem is? – thefourtheye Nov 21 '13 at 05:07
  • 2
    Stack Overflow is not a debugger. – Jonathon Reinhart Nov 21 '13 at 05:08
  • What does the output look like? Also, where is the body of your main method? – Elliott Frisch Nov 21 '13 at 05:10
  • Guys, guys, i know the question isn't very clear, but it's only been 3 minutes and i don't think it has to be closed just yet. He can edit it, and i'm pretty sure he would make it clearer. It's his first post here! Don't create such a negative atmosphere. – aIKid Nov 21 '13 at 05:11
  • I don't know what to do to get it to add up the occurrences of each number each time it reads a line and then save them in variables. Or save each total in a list – user3015970 Nov 21 '13 at 05:11
  • @user3015970 This would help! :) http://stackoverflow.com/questions/893417/item-frequency-count-in-python – tmj Nov 21 '13 at 05:12

1 Answers1

2
def countLines(file, outfile):
    s = file.read()
    result = [s.count(str(i)) for i in range(10)]
    ...

More efficient to scan s just once (but a bit more code)

def countLines(file, outfile):
    s = file.read()
    result = [0] * 10
    for c in s:
        if c.isdigit():
            result[int(c)] += 1
    ...
John La Rooy
  • 263,347
  • 47
  • 334
  • 476