首页 > 解决方案 > 字典:按字母顺序排列列表的元素并计算其出现次数

问题描述

嗨所以我一直在尝试计算我制作的列表中的元素,以及当我这样做的时候

结果应该是:

a 2 超过 2 超过 1 等等。

这是我得到的:

word = []
with open('Lateralus.txt', 'r') as my_file:
    for line in my_file:
       temporary_holder = line.split()
          for i in temporary_holder:
             word.append(i)

for i in range(0,len(word)): word[i] = word[i].lower()    

word.sort()

for count in word:
    if count in word:
       word[count] = word[count] + 1
else:
    word[count] = 1

for  (word,many)  in word.items(): 
    print('{:20}{:1}'.format(word,many))

标签: python-2.7listdictionary

解决方案


@Kimberly,正如我从您的代码中了解到的那样,您想要读取一个字母字符的文本文件。您还想忽略文件中字母字符的情况。最后,您要计算文本文件中每个唯一字母的出现次数。

我会建议你为此使用字典。我为此任务编写了一个示例代码,它满足以下 3 个条件(如果您希望通过提供输入和预期输出来获得不同的结果,请发表评论,我将基于此更新我的代码):

  1. 读取文本文件并通过删除中间的任何空格来创建单行文本。

  2. 它将大写字母转换为小写字母。

  3. 最后,它创建了一个包含唯一字母及其频率的字典。

» 横向.txt

abcdefghijK
ABCDEfgkjHI
IhDcabEfGKJ
mkmkmkmkmoo
pkdpkdpkdAB
A B C D F Q
ab abc ab c

“ 代码

import json

char_occurences = {}

with open('Lateralus.txt', 'r') as file:
    all_lines_combined = ''.join([line.replace(' ', '').strip().lower() for line in file.readlines()])

print all_lines_combined      # abcdefghijkabcdefgkjhiihdcabefgkjmkmkmkmkmoopkdpkdpkdababcdfqababcabc
print len(all_lines_combined) # 69 (7 lines of 11 characters, 8 spaces => 77-8 = 69)

while all_lines_combined:
    ch = all_lines_combined[0]

    char_occurences[ch] = all_lines_combined.count(ch)

    all_lines_combined = all_lines_combined.replace(ch, '') 

# Pretty printing char_occurences dictionary containing occurences of 
# alphabetic characters in a text file
print json.dumps(char_occurences, indent=4)

"""
    {
        "a": 8,
        "c": 6,
        "b": 8,
        "e": 3,
        "d": 7,
        "g": 3,
        "f": 4,
        "i": 3,
        "h": 3,
        "k": 10,
        "j": 3,
        "m": 5,
        "o": 2,
        "q": 1,
        "p": 3
    }
"""

推荐阅读