0006-日记找词

代码

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]  # 列表推导式
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容