2011-10-10 115 views
0

當我運行程序時,函數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() 
+0

使用'collections.Counter'這些工作 – JBernardo

+0

BTW你的鱈魚e非常和諧...... – JBernardo

回答

1

您應該檢查freq的值。如果值爲0,則循環將永不運行且percentagefreq不會返回值。

望着循環,

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

freq將有最後的值(計(Z)),這是最有可能爲零。

+0

請注意,即使'freq'不是0,該函數也只能返回一次。如果你想要一個值列表,那麼你必須自己構建它,例如列表理解,或者通過編寫和使用該函數作爲生成器。 –

+0

還要注意,你有'countFreq'的同樣的問題:你每次通過循環重新分配給全局變量,它取代了以前的值。 –

+0

另外請注意,即使你正確地爲'freq'設定了一個列表,'我在range(freq)中''並不意味着'每個'freq'的值都是';它意味着「頻率」 - 多次,帶有一個計數器「。如果你**做了一個列表,那麼這將會中斷,因爲列表不是一個有效的操作次數。另外,傳遞一個全局變量的信息是醜陋的;使用參數,就像你做其他事情一樣。 –

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)) 
+0

如果我想添加一個函數來查找經常出現的信件,那麼該怎麼辦?我使用:def maxchar(百分比)m =最大(freq)返回m,但它返回0 – user986956

+0

請研究參數傳遞如何工作以及如何返回值。 –