Python中文件的字符频率

时间:2015-05-16 00:12:04

标签: python

所以我有这个代码可以给我一个文件中所有字母的频率,但我想找到每个第5个字母的频率。有人可以帮助我吗?

<%@ page trimDirectiveWhitespaces="true" %>

1 个答案:

答案 0 :(得分:2)

使用字典

#make the dictionary
char_dict = {}

#open the file
with open('my_file.txt') as the_data:

    #read the data in as a string
    the_data_string = the_data.read()

    #loop over every 5th character in the string using slicing
    for each in the_data_string[::5]:

        #try add +1 to the key that the character is located in
        try:
            char_dict[each] += 1

        #if the key doesn't exist, make a new key with the value of 1
        except KeyError:
            char_dict[each] = 1

然后,您可以使用list(char_dict.keys())或仅使用list(char_dict.values())

的值将这些键作为列表读出