Random
int
k unique samples
print 会自动换行,print(end="")会取消换行,end为结束后缀
遍历文件
os.walk()
Python method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.
string check contains
str = "Messi is the best soccer player" >>> "soccer" in str True >>> "football" in str False
三引号
三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。
元组和列表
元组是不可变的, 而列表是可变的。
我们可以修改列表的值,但是不能修改元组的值。
由于列表是可变的,我们不能将列表用作字典中的key。 但可以使用元组作为字典key。
同构与异构
习惯上元组多用于用于存储异构元素,异构元素即不同数据类型的元素,比如(ip,port)。 另一方面,列表用于存储异构元素,这些元素属于相同类型的元素,比如[int1,in2,in3]。
list
reverse sublist
a[start:stop:step] # start through not past stop, by step
step为-1的时候是reverse order
a[:-11:-1] # the last 10 items, reversed
sort
The sort() method doesn't return any value. Rather, it changes the original list.
list.sort(key=..., reverse=...)
If you want a function to return the sorted list rather than change the original list, use sorted().
sorted(list, key=..., reverse=...)
paramter
reverse - If True, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison
JSON
Python list(dict) to json string
json.dumps 用于将 Python 对象编码成 JSON 字符串。
[{"b": 2, "d": 4, "a": 1, "c": 3, "e": 5}]
json string to python list(dict)_
json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
打包并压缩
把当前目录下所有文件打包压缩成a.tar.zip
解压
-C 指定目录
爬虫
request模块:
requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/
requests.get(url)可以发送一个http get请求,返回服务器响应内容。
BeautifulSoup库:
BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库。网址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml。
BeautifulSoup(markup, "html.parser")或者BeautifulSoup(markup, "lxml"),推荐使用lxml作为解析器,因为效率更高。
通过tag标签逐层查找:
soup.select("body a")
获取属性
tag.get('href')
或者
tag['href']
如果不确定某个属性是否存在时,用 tag.get('attr') 方法去获取它,跟获取Python字典的key一样
tag['class']
KeyError: 'class'
print(tag.get('class'))
None
jsonp to json
response_json = response[ response.index("(") + 1 : response.rindex(") }
catch")]
或者get请求的时候,去掉callback=,则会返回json
动态请求
如果数据是动态加载,可以在浏览器network里查看请求的api
写入文件
With the "With" statement, you get better syntax and exceptions handling.
"The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks."
In addition, it will automatically close the file. The with statement provides
a way for ensuring that a clean-up is always used.
with 省去写exception handler和close file
pandas
read csv
df = pd.read_csv('tag.csv')
dataframe
cut
value_counts
df.value_counts() 以Series形式返回指定列的不同取值的频率,默认按频率从高到低排序
groupby
matplot
size
plt.figure(figsize=(12, 12))
%matplotlib inline
%matplotlib inline 可以在Ipython编译器里直接使用,功能是可以内嵌绘图,并且可以省略掉plt.show()这一步
pie
参数:
x :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;
labels :(每一块)饼图外侧显示的说明文字;
explode :(每一块)离开中心距离;
startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;
shadow :在饼图下面画一个阴影。默认值:False,即不画阴影;
正圆
plt.axis('equal')
string format
python >3.6
>>> name = 'hoxis'
>>> age = 18
>>> f"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
百分号
%%表示百分号
>>> print('数据的比例是:%.2f%%' %(scale * 100))
数据的比例是:10.00%
>>> print('数据的比例是:%d%%' %(scale * 100))
数据的比例是:10%
词云
matlibplot 加载中文字体
如果没成功,尝试
jieba 分词
停用词
字典 .get(key,value) value为如果不存在返回的值,counts.get(word, 0): word不存在于counts中则返回 0
中文常用停用词词表
多进程
多进程共同的全局变量,需要使用特殊方式声明:
多进程list 使用前需转换回普通list, list(lis)
.join() 可以等待进程执行结束后再输出
多进程的一个大坑:broken pipe
解决方案不要在主线程外使用shared object,这样主线程使用的时候修改,会影响子线程的这个object
解决方案:移除主线程的修改,或者把修改放到子线程跑完之后
解释
.join()
主线程等待子线程跑完。python默认是先执行完主线程
这样主线程就会阻塞了
参考