collections.Counter()

面试题:使用python打印出文件中出现次数最高的10个单词及其出现次数。 


import re,collections


words=re.findall('\w+',open(r'D:\zip.txt').read().lower())


print collections.Counter(words).most_common(10)


\w (查找字母)When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. 



from collections import Counter

def main():
    print Counter("I am a boy") # Counter({' ': 3, 'a': 2, 'b': 1, 'I': 1, 'm': 1, 'o': 1, 'y': 1})
    #输出出现次数最多的前3个字符
    print Counter("I am a boy").most_common(3) # [(' ', 3), ('a', 2), ('b', 1)]
    

if __name__ == '__main__':
    main()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值