selfteaching / selfteaching/selfteaching-python-camp
Day09 神器的Counter函数
Open
Nobody has claimed this yet.
学习心得分享
- Dominant language
- Python
- Stars
- 151
- Forks
- 875
- PR merge metrics
- No merged PRs in 30d
Description
今天在原项目上增加了,使用Counter 这个函数,这个函数的设计真是太神奇了,看过文档原本以为他的正确使用方式是
cnt = Counter()
for item in str_list
cnt[item] += 1
print(cnt)
在我提交完作业,偷瞄了一眼同桌的同学是这样写的
cnt = Countter(str_list)
直接一句话就可以了,当时我都震惊了
这里面完成了多少动作你知道吗:
- 将传入数组中的元素去重,分类
- 将数组转换成dict
- 遍历数组中的元素,遇到相同在分类中累加
- 按照value排序
这样分析过后,发现这个函数简直就是为了处理词频而诞生的工具
- 还有今天加上了文件处理,也就是读取文件这里有个坑,想读取文件首先你得找到文件在哪,
直接使用open()打开的是工作目录(项目的根文件夹selfteaching..这个文件夹)其实使用open(./19100xx/xiaoming/...)这样一层层找也能找得到但这样太麻烦了,而文档又偏偏没写这段,所以你得使用Google我找到的是
from os import path
path_file = path.dirname(path.realpath(__file__))
这样直接找到的就是当前目录的绝对路径(以 "/" 开头的路径)
- 当我们成功的将<唐诗300首>导入到变量当中就会遇见第二个坑,无论怎么都不能读出contents type author 中的数据,
我们得到的不是json格式的数据(一种结构化的数据格式),而是一个一个的字符串,当然我们直接用以前的程序,过滤一遍英文同样也能搞定
这时候我们就可以使用json.loads(read_data)将读到的字符串格式化一下(不是U盘的格式化,删除数据意思)这样就可以得到一个结构化的数据,而不是字符串了这样我们就可以使用
for item in read_data:
text += item['contents'] + item['type'] + item['author']
return text
把里面所有出现中文的部分连接起来
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue is a Chinese learning note about Python Counter, file paths, and JSON parsing, but it names no file, test, or entry point. First clarify whether any repository documentation should be added or changed; completion cannot be defined from the current issue text.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 10/100