Python 我的函数没有返回预期值

Python 我的函数没有返回预期值,python,Python,当我运行程序时,函数percentagefreq返回“无” 我做错了什么 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 l

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

我做错了什么

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()
def main():
文件=原始输入(“请输入文件名:”)
s=读取文件(文件)
打印
打印“文件包含:”
印刷品
lc=小写字母
打印“小写文件为:”
打印信用证
打印
compressedText=nospaces(lc)
打印“仅字母字符为:
打印压缩文本
打印
计数=α(lc)
nonchr=len(s)-计数
打印“字母字符数为:”,计数
print“非字母字符的数量为:”,nonchr
打印
打印“字母\t频率\t百分比”
countFreq(压缩文本)
百分比=百分比频率(计数)
打印百分比
def readfile(文件):
文本=打开(文件“r”)
s=text.read()
text.close()
返回s
def tolowercase(s):
lc=“”
对于s中的x:

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

看看循环

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

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

很抱歉,你做的几乎都是错的。我对另一个答案的评论解释了几个问题。以下是一些其他改进:

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


请注意,即使
freq
不是0,函数也只能
返回一次。如果您想要一个值列表,那么您必须自己构建它,例如通过列表理解,或者通过编写函数并将其用作生成器。还要注意的是,
countFreq
也有同样的问题:每次通过循环,您都会重新分配给全局变量,它替换了以前的值。还要注意,即使您正确地列出了
freq
范围内i(freq)
并不意味着“使用
freq
的每个值”;它的意思是“
freq
-多次,带计数器”。如果你真的列了一个清单,那就错了,因为清单不是做某事的有效次数。而且,用全局变量传递信息也很难看;使用参数,就像你对其他任何事情所做的那样。对这些作业使用
集合。计数器
。你的代码非常不和谐…如果我想添加一个函数来查找mots频繁出现的字母,该怎么办。我使用了:def maxchar(percent)m=max(freq)return m,但它返回0请研究参数传递的工作原理,以及返回值的工作原理。
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))