10 月 292020
 
# -*- coding:utf-8 -*-
import string

# 输出所有标点符号!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.punctuation)
# https://docs.python.org/zh-cn/3/library/stdtypes.html#str.strip
# strip()方法返回原字符串的副本,移除其中的前导和末尾字符。不指定参数则移除空格。
# https://docs.python.org/zh-cn/3/library/string.html#string.punctuation
# 字符串常量,返回被视为标点符号的 ASCII 字符所组成的字符串
# https://docs.python.org/zh-cn/3/library/functions.html#func-set
# set()函数,返回集合对象。
# set()函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。


path = 'C:/Users/harveymei/Desktop/news.txt'

with open(path, 'r') as text:
    # 循环读取分割单词赋值变量写入列表并对元素去除标点符号并转换为小写
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words)  # 使用set()函数将列表中的字符去重复后赋值变量
    # 循环获取列表元素作为key,并将words列表中元素计数值作为value,生成字典并赋值变量
    counts_dic = {index: words.count(index) for index in words_index}

# https://docs.python.org/zh-cn/3/library/functions.html#sorted
# 根据 iterable 中的项返回一个新的已排序列表。
# 具有两个可选参数,它们都必须指定为关键字参数。
# key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如 key=str.lower)。 默认值为 None (直接比较元素)。
# reverse 为一个布尔值。 如果设为 True,则每个列表元素将按反向顺序比较进行排序。
# https://docs.python.org/zh-cn/3/howto/sorting.html#key-functions
# key 形参用来指定在进行比较前要在每个列表元素上调用的函数(或其他可调用对象)。
# https://docs.python.org/zh-cn/3/reference/expressions.html?highlight=lambda#lambda
# lambda 表达式(有时称为 lambda 构型)被用于创建匿名函数。

for word in sorted(counts_dic, key=lambda x: counts_dic[x], reverse=True):  # 循环对字典中元素按照计数值反向排序并赋值变量
    print('{} -- {} times'.format(word, counts_dic[word]))  # 使用格式化字符串打印单词及对应计数值
C:\Users\harveymei\PycharmProjects\mod3736\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/mod3736/static.py
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
the -- 14 times
a -- 4 times
in -- 4 times
and -- 4 times
that -- 4 times
leads -- 2 times
created -- 2 times
practice -- 2 times
such -- 2 times
china -- 2 times
has -- 2 times
said -- 2 times
legislature -- 2 times
party -- 2 times
li -- 2 times
experience -- 2 times
process -- 2 times
is -- 2 times
adding -- 2 times
government -- 2 times
roles -- 2 times
good -- 2 times
governance -- 2 times
cpc -- 2 times
due -- 2 times
work -- 2 times
formulation -- 2 times
their -- 2 times
of -- 2 times
play -- 2 times

Process finished with exit code 0