我的函数没有返回预期值

时间:2011-10-10 02:03:49

标签: python

当我运行程序时,函数percentagefreq返回“none”。

我做错了什么?

def main():
    file = raw_input("Please enter name of file: ")
    s = readfile(file)
    print
    print "The file contains:"
    print s
    lc = tolowercase(s)
    print "The file in lowercase is:"
    print lc
    print
    compressedTxt = nospaces(lc)
    print "The alphabetic characters alone are:"
    print compressedTxt
    print
    Count = alpha(lc)  
    nonchr = len(s) - Count
    print "The number of alphabetic characters are: ", Count
    print "The number of non-alphabetic charcters are: ", nonchr
    print
    print "Letter\tFrequency\tPercentage"
    countFreq(compressedTxt)
    percent = percentagefreq(Count)
    print percent


def readfile(file):
    text = open(file,"r")
    s = text.read()
    text.close()
    return s

def tolowercase(s):
    lc = ""
    for x in s:
        if "A" <= x <= "Z":
            lc = lc + chr(ord(x) + 32)
        else:
            lc = lc + x
    return lc

def nospaces(lc):
    compressedTxt = ""
    for x in lc:
        if "a" <= x <= "z":
            compressedTxt = compressedTxt + x

    return compressedTxt


def alpha(lc):
    Count = 0
    for x in lc:
        if "a" <= x <= "z":
            Count = Count + 1
    return Count


def countFreq(compressedTxt):
    global freq
    freq = ""
    az = ('abcdefghijklmnopqrstuvwxyz')
    for x in az:
        freq = compressedTxt.count(x)
        print x, "\t", freq,"\t"

def percentagefreq(Count):
    for i in range(freq):
        percent = i/Count
        return percent

#I am trying to calculate the percentage of each letter appearing in a file of text

main()

2 个答案:

答案 0 :(得分:1)

您应该检查freq的值。如果值为0,则循环将永远不会运行,percentagefreq将不会返回值。

看着循环,

for x in az:
    freq = compressedTxt.count(x)
    print x, "\t", freq,"\t"

freq将具有最可能为零的最后一个值(count(z))。

答案 1 :(得分:1)

你说的几乎都是错的,不好意思。我对另一个答案的评论解释了几个问题。以下是其他一些改进:

def main():
    # There is really no reason to pull out a separate function
    # for something as simple as opening and reading a file. It
    # can be done in one line, and the following is a simpler way
    # of handling the file-closing logic:
    filename = raw_input("Please enter name of file: ")
    with open(filename) as f: s = f.read()
    print
    print "The file contains:"
    print s
    # Again, lowercasing is built right in; no reason to write it yourself.
    lc = s.lower()
    print "The file in lowercase is:"
    print lc
    print
    # 'nospaces' is a bad name for your function because you're
    # actually removing everything that's not a letter.
    # Again, there is a trivial one-liner for this:
    compressed = filter(str.isalpha, lc)
    print "The alphabetic characters alone are:"
    print compressed
    print
    # There is a much simpler way to count the alphabetic
    # and non-alphabetic characters: we already have the
    # string of all the alphabetic characters, and strings
    # know how long they are, so:
    Count = len(compressed)
    nonchr = len(s) - Count
    print "The number of alphabetic characters are: ", Count
    print "The number of non-alphabetic charcters are: ", nonchr
    print
    print "Letter\tFrequency\tPercentage"
    # Your logic is entirely messed up here: you can't print all the
    # letters and frequencies, and then magically go back and insert
    # the percentages. You need to calculate the frequencies first, then
    # calculate the percentages from the frequencies, and then you can
    # print everything out.
    # Again, counting the frequencies and actually building a list
    # (as you need) is a one-liner:
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    # By the way, notice how I'm not abbreviating my names?
    frequencies = [compressedTxt.count(letter) for letter in alphabet]
    # that is: stop trying to tell Python how to put together a list of data,
    # and ask it for the data you want. Similarly:
    percentages = [f / float(Count) for f in frequencies]
    # Notice the conversion there: if you just divide through with two integers,
    # you will throw away the remainder (which for your case means you'll get 0
    # for every value).
    # Now we'll output the data, by using the built-in 'zip' function
    # to take pairs of data from the two lists:
    for l, f, p in zip(alphabet, frequencies, percentages):
        print l, '\t', f, '\t', p


main()

如果没有评论和诊断,我们会得到一些简单的内容:

def main():
    filename = raw_input("Please enter name of file: ")
    with open(filename) as f: data = filter(str.isalpha, f.read().lower())
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    frequencies = [data.count(letter) for letter in alphabet]
    percentages = [f / float(len(data)) for f in frequencies]
    print "Letter\tFrequency\tPercentage"
    for l, f, p in zip(alphabet, frequencies, percentages):
        print l, '\t', f, '\t', p

或者,更简单地说,您可以只计算循环中的值(上面主要是为了显示实际以您希望的方式传递数据所需的技术):

def main():
    filename = raw_input("Please enter name of file: ")
    with open(filename) as f: data = filter(str.isalpha, f.read().lower())
    print "Letter\tFrequency\tPercentage"
    for letter in 'abcdefghijklmnopqrstuvwxyz':
        frequency = data.count(letter)
        print letter, '\t', frequency, '\t', frequency / float(len(data))