【问题标题】:Dictionary: Alphabetize the elements of a list and count its occurences字典:按字母顺序排列列表的元素并计算其出现次数
【发布时间】:2018-11-09 07:31:14
【问题描述】:

嗨,我一直在尝试计算我制作的列表中的元素,以及我何时计算

结果应该是:

一个 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))

【问题讨论】:

  • 请修正语法错误,以便此处提供的代码能够真正运行。另外,请提供一个小样本输入(Lateralus.txt 的内容)并显示预期输出。还要描述你的代码做错了什么;如果您遇到异常,请包含完整的回溯。
  • (如果您在为 StackOverflow 格式化代码时遇到问题,请尝试以下操作:编辑您的问题,再次粘贴代码,然后立即单击并拖动以将其全部选中,然后单击 {} 中的按钮界面或按Ctrl-K。)

标签: python-2.7 list dictionary


【解决方案1】:

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

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

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

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

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

» Lateralus.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
    }
"""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2021-03-14
    • 2023-02-17
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多