如何用python找辅音字母最多的单词?

有一个txt文件里面是很多很多单词。文件名:123.txt
如果一个单词只有辅音字母(除了a,e,i,o,u以外的字母),没有元音字母(a,e,i,o,u),那么这个单词放进第一个list。
对于有辅音也有元音的单词,找出每个单词有多少个辅音,有多少个元音,然后用辅音数除以元音数算出一个ratio。把这个ratio最大的那些单词放进第二个list. 最后print出这两个list.
例如:如果txt文件里的单词是"The", "Zen", "of", "spy",那最后print出的两个lists应该是['spy'] 和 ['The', 'Zen'] ,因为spy只有辅音字母,“the”和“zen"的ratio最大,是2.

请问这一系列python code要怎么写?谢谢!

def top_ratios():
pass

if(__name__ == "__main__"):
print(top_ratios())

#!/usr/bin/env python
# coding: utf-8
#
# author: Tim Wang
# filename: baidu.py
# date: Apr., 2014

import re

def top_ratios(context):
    words = [word.lower() for word in re.findall('\w+', context)]
    patt_vowel = re.compile('[aeiou]')
    onlyconsonant = []
    ratiosdict = {}
    for word in words:
        vowels = len(patt_vowel.findall(word))
        if vowels:
            ratio = 1. * (len(word) - vowels) / vowels
            ratiosdict.setdefault(ratio, set()).add(word)
        else:
            onlyconsonant.append(word)
    return (onlyconsonant, 
            list(sorted(ratiosdict.items(), reverse=True)[0]))

if __name__ == "__main__":
    onlyconsonant, ratios = top_ratios(open('123.txt').read())
    print onlyconsonant
    print ratios

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-13
你好,你的思路很清晰的,
完全可以自己实现一下的:
1:先设定两个元组,元音和辅音
2:遍历文件,每次取一个单词(如果多个就分开来)
3:分割单词成单个,然后依次比较单词里面的字母是元音还是辅音,并计数
4:求比率,追加到数组中。
相似回答