【问题标题】:Reading a text file to print frequency of letters in decreasing order - Python 3读取文本文件以按降序打印字母的频率 - Python 3
【发布时间】:2018-02-22 01:24:47
【问题描述】:

我正在做 python 基本挑战,这是其中之一。我需要做的就是阅读一个文件并按降序打印出字母的频率。我可以做到这一点,但我想通过打印频率百分比以及字母 - 频率 - freq% 来增强程序。像这样的东西:o - 46 - 10.15%

这是我到目前为止所做的:

def exercise11():
    import string
    while True:
        try:
            fname = input('Enter the file name -> ')
            fop = open(fname)
            break
        except:
            print('This file does not exists. Please try again!')
            continue

    counts = {}
    for line in fop:
        line = line.translate(str.maketrans('', '', string.punctuation))
        line = line.translate(str.maketrans('', '', string.whitespace))
        line = line.translate(str.maketrans('', '', string.digits))
        line = line.lower()
        for ltr in line:
            if ltr in counts:
                counts[ltr] += 1
            else:
                counts[ltr] = 1
    lst = []
    countlst = []
    freqlst = []
    for ltrs, c in counts.items():
        lst.append((c, ltrs))
        countlst.append(c)
    totalcount = sum(countlst)
    for ec in countlst:
        efreq = (ec/totalcount) * 100
        freqlst.append(efreq)
    freqlst.sort(reverse=True)
    lst.sort(reverse=True)
    for ltrs, c, in lst:
        print(c, '-', ltrs)

exercise11()

如您所见,我可以在不同的列表中计算和排序 freq%,但我无法将它与字母 freq 一起包含在 lst[] 列表的元组中。有没有办法解决这个问题?

另外,如果您对我的代码有任何其他建议。请务必提及。 Output Screen


修改

应用@wwii 提到的简单修改,我得到了所需的输出。我所要做的就是在迭代lst[] 列表时再向打印语句添加一个参数。以前我尝试为 freq% 创建另一个列表,排序,然后尝试将其插入到列表中的字母计数元组中,但没有成功。

 for ltrs, c, in lst:
        print(c, '-', ltrs, '-', round(ltrs/totalcount*100, 2), '%')

Output Screen

【问题讨论】:

  • 你必须使用元组吗?如果您只是使用列表,则不应遇到此问题。元组是不可变的
  • @NahuelP 是的,要对频率进行排序,我需要在列表中有一个元组来关联频率和字母。
  • 那么@wwi 的回答正确吗?
  • @EzizDurdyyev 是的,它也是解决我的问题的最简单的修改。
  • @SrijanSingh 所以你应该接受这个答案

标签: python python-3.x list dictionary tuples


【解决方案1】:

您的计数数据位于{letter:count} 对的字典中。

您可以像这样使用字典来计算总数:

total_count = sum(counts.values())

然后在迭代计数之前不要计算百分比......

for letter, count in counts.items():
    print(f'{letter} - {count} - {100*count/total}')    #Python v3.6+
    #print('{} - {} - {}'.format(letter, count, 100*count/total)    #Python version <3.6+

或者,如果您想将所有内容放在一个列表中以便对其进行排序:

data = []
for letter, count in counts.items():
    data.append((letter,count,100*count/total)

使用operator.itemgetter作为排序键功能可以提高代码的可读性。

import operator
letter = operator.itemgetter(0)
count = operator.itemgetter(1)
frequency = operator.itemgetter(2)

data.sort(key=letter)
data.sort(key=count)
data.sort(key=frequency)

【讨论】:

    【解决方案2】:

    元组是不可变的,这可能是您发现的问题。另一个问题是sort 函数的简单形式;一个更高级的sort 函数会很好地为您服务。见下文:

    lst 的元组列表格式,但是因为元组是不可变的而列表是可变的,所以选择将 lst 更改为列表列表是一种有效的方法。然后,由于lst 是一个列表列表,其中每个元素由“字母、计数、频率%”组成,因此可以使用带有lambda 的排序函数按您想要的任何索引进行排序。以下内容将插入您的for line in fop: 循环之后。

    lst = []
    for ltrs, c in counts.items():
        lst.append([ltrs,c])
    totalcount = sum([x[1] for x in lst])       # sum all 'count' values in a list comprehension
    
    for elem in lst:
        elem.append((elem[1]/totalcount)*100)   # now that each element in 'lst' is a mutable list, you can append the calculated frequency to the respective element in lst
    
    lst.sort(reverse=True,key=lambda lst:lst[2])    # sort in-place in reverse order by index 2.
    

    【讨论】:

    • 不知道为什么我们需要关注元组的不变性。列表的 len 都是一样的。只需使用 zip() 将它们放在一起。也就是说,高级排序肯定是这里的方法:) 我们同意。干杯
    【解决方案3】:

    freqlst、countlist 和 lst 中的项目通过它们的位置相互关联。如果有任何排序,则该关系将丢失。

    在排序前将列表压缩将保持关系。

    将从您的列表初始化行中选取。

    lst = []
    countlst = []
    freqlst = []
    for ltr, c in counts.items():
        #change here, lst now only contains letters
        lst.append(ltr)
        countlst.append(c)
    totalcount = sum(countlst)
    for ec in countlst:
        efreq = (ec/totalcount) * 100
        freqlst.append(efreq)
    
    #New stuff here: Note this only works in python 3+
    zipped = zip(lst, countlst, freqlst)
    zipped = sorted(zipped, key=lambda x: x[1])
    
    for ltr, c, freq in zipped:
        print("{} - {} - {}%".format(ltr, c, freq)) # love me the format method :)
    

    基本上,zip 将列表组合成一个元组列表。然后您可以使用 lambda 函数对这些元组进行排序(非常常见的堆栈问题)

    【讨论】:

    • 唯一的缺陷是它在输出屏幕中打印了两次 freq(counts),一次是在 lst[] list 内的元组中,第二次是在 countlst 列表中。
    • 是的,对不起。通过删除第一个 for 循环中的元组创建,这非常容易解决。我试图说明一个解决方案。我会修复的。如果这有帮助,请考虑接受它
    【解决方案4】:

    我想我能够通过使用列表而不是元组来实现您想要的。元组不能修改,但如果你真的想知道如何点击here

    (我还添加了退出程序的可能性)

    重要提示:永远不要忘记评论您的代码

    代码:

    def exercise11():
        import string
        while True:
            try:
    
                fname = input('Enter the file name -> ')
                print('Press 0 to quit the program') # give the User the option to quit the program easily
                if fname == '0':
                    break
                fop = open(fname)
                break
            except:
                print('This file does not exists. Please try again!')
                continue
    
        counts = {}
        for line in fop:
            line = line.translate(str.maketrans('', '', string.punctuation))
            line = line.translate(str.maketrans('', '', string.whitespace))
            line = line.translate(str.maketrans('', '', string.digits))
            line = line.lower()
            for ltr in line:
                if ltr in counts:
                    counts[ltr] += 1
                else:
                    counts[ltr] = 1
        lst = []
        countlst = []
        freqlst = []
    
        for ltrs, c in counts.items():
            # add a zero as a place holder & 
            # use square brakets so you can use a list that you can modify 
            lst.append([c, ltrs, 0]) 
            countlst.append(c)
        totalcount = sum(countlst)
    
        for ec in countlst:
            efreq = (ec/totalcount) * 100
            freqlst.append(efreq)
        freqlst.sort(reverse=True)
        lst.sort(reverse=True)
    
        # count the total of the letters 
        counter = 0
        for ltrs in lst:
            counter += ltrs[0]
    
        # calculate the percentage for each letter 
        for letter in lst:
            percentage = (letter[0] / counter) * 100
            letter[2] += float(format(percentage, '.2f'))
    
        for i in lst:
            print('The letter {} is repeated {} times, which is {}% '.format(i[1], i[0], i[2]))
    exercise11()
    

    【讨论】:

      【解决方案5】:
      <?php
      
      $fh = fopen("text.txt", 'r') or    die("File does not exist");
       $line = fgets($fh); 
      
       $words = count_chars($line, 1); 
      
      foreach ($words as $key=>$value)
         {
         echo "The character  <b>' ".chr($key)." '</b>  was found   <b>$value</b>   times. <br>";
         }
      
      ?>
      

      【讨论】:

      • 欢迎使用代码示例,但也请说明您的解决方案
      • 此代码用于读取字符数以及它们在文件中的重复频率。
      猜你喜欢
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多