python-2.7 - 字典:按字母顺序排列列表的元素并计算其出现次数
问题描述
嗨所以我一直在尝试计算我制作的列表中的元素,以及当我这样做的时候
结果应该是:
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))
解决方案
@Kimberly,正如我从您的代码中了解到的那样,您想要读取一个字母字符的文本文件。您还想忽略文件中字母字符的情况。最后,您要计算文本文件中每个唯一字母的出现次数。
我会建议你为此使用字典。我为此任务编写了一个示例代码,它满足以下 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
}
"""
推荐阅读
- javascript - 在单元测试中覆盖注入令牌
- ios - 如何增加 UITableView 中自定义单元格的宽度
- python-3.x - 如何在 Pytorch 中创建自己的损失函数?
- python - Cprofile 结果中的“{method 'recv_into' of '_socket.socket' objects}”是什么?我怎样才能减少它的时间消耗?
- websocket - websocket_sockJS:所有传输错误。添加 { 传输后:['websocket']}
- c# - Linq to Xml:删除命名空间
- python - 将数据上传到 Django REST API 时没有提交文件错误
- amazon-web-services - S3 复制:访问被拒绝:Amazon S3 无法检测是否在目标存储桶上启用了版本控制
- printing - 更改 CUPS 打印机名称
- c# - 我创建了一个新的对象类型,但出现错误“没有解析器”