程序必须计算每行中每个数字的出现次数

时间:2013-11-21 05:06:49

标签: python count numbers

程序必须使用长度为10的列表来计算10位数字0-9的出现次数。

它应该像这样打印:

我不知道如何在每次读取一行时添加每个数字的出现次数。或者如何将总数列入列表。

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

1 个答案:

答案 0 :(得分:2)

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

更有效地扫描s一次(但更多代码)

def countLines(file, outfile):
    s = file.read()
    result = [0] * 10
    for c in s:
        if c.isdigit():
            result[int(c)] += 1
    ...