嗨,所以我一直在尝试计算列表中的元素,以及我做的时候
结果应为:
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))
答案 0 :(得分:0)
@Kimberly ,正如我从您的代码中所理解的,您想要读取字母字符的文本文件。 您还想忽略文件中字母字符的大小写。最后,您想要计算文本文件中每个唯一字母的出现次数。
我建议您使用词典。我已为此任务编写了示例代码 满足以下3个条件(如果您想通过提供输入和预期输出来获得不同的结果,请发表评论,我将根据此更新我的代码):
读取文本文件并通过删除其间的任何空格来创建单行文本。
它将大写字母转换为小写字母。
- 醇>
最后,它会创建一个包含带有频率的唯一字母的字典。
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
}
"""