python统计英文首字母出现的次数
使用python解析有道词典导出的xml格式单词,统计各个首字母出现的次数,并按次数由多到少进行排序
相关实现
导出的xml格式如下
<wordbook>
<item>
<word>portion</word>
<trans><![CDATA[n. 部分;一份;命运vt. 分配;给…嫁妆]]></trans>
<phonetic><![CDATA[['pɔːʃ(ə)n]]]></phonetic>
<tags></tags>
<progress>2</progress>
</item>
</wordbook>
使用python3自带的xml解析器进行解析,使用字典进行保存统计结果
import time
import xml.etree.ElementTree as et
# get all word
def get_all_word(uri):
tree = et.parse(uri)
root = tree.getroot()
return root.findall('./item/word')
# calculate the first letter frequency of words
def cal_aleph(word_list):
# define dwords to save first letter count
dwords = {}
for cword in word_list:
letter = cword.text.strip()[0].lower()
# judge the letter is english letter
echar = ord(letter)
if(echar >= 97 and echar <= 122):
try:
dwords[letter] += 1
except KeyError:
dwords[letter] = 1;
# order by count desc
dwords = sorted(dwords.items(), key=lambda line:line[1], reverse=True)
return dwords
if __name__ == '__main__':
start_time = time.time()
word_list = get_all_word(r'd:\pyzone\youdao.xml')
result = cal_aleph(word_list)
for row in result:
print("%s : %d"%(row[0], row[1]))
end_time = time.time()
print('Costed time: ' + str((end_time - start_time)) + 's')
统计结果如下:
回顾
- 使用
xml.etree.ElementTree
的parse解析指定路径的xml文件,root.findall查找指定节点 - sorted方法对列表进行排序
- '中文'.isalpha() 结果为True