代码
import re
def get_words(text):
words = re.findall('(\w+)\s', text)
return words
def get_counter(words):
words_set = set(words)
dic_word_num = {}
for word in words_set:
dic_word_num[word] = words.count(word)
print(max(dic_word_num.items(), key=lambda x:x[1]))
with open('text.txt') as text:
text = text.read()
get_counter(get_words(text))
新知识
1)列表转集合,去重
set_list = set(my_list)
2)max函数,第一个参数为一个可迭代对象,如果key没有指定,就是默认取最大,如果key参数有指定,就按指定规则来比较
3)匿名函数,参数是x,返回结果是x[1],就是value的值,一般用在max函数的key上
lambda x: x[1]
4)返回python_code
文件夹里面的py文件的路径
glob.glob('/home/kk/python_code/FlaskAuth/*.py')
['/home/kk/python_code/FlaskAuth/run.py', '/home/kk/python_code/FlaskAuth/FlaskAuth.py', '/home/kk/python_code/FlaskAuth/hello.py']
5)返回列表中出现次数最多的元素
from collections import Counter
Counter(my_list).most_common(1)
6)map使用
map(f, iterable)
基本上等于:
[f(x) for x in iterable] # 列表推导式
网友评论