面试题:使用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()