今天看到一篇关于Python的30个提示和技巧的文章,有以下11条觉得很有意思,在这里记录并分享下。
1. Use Python 3
首先,最重要的是使用Python 3,因为 Python 2 is officially not supported as of January 1, 2020
2. Use IPython
IPython是一个增强版的Shell,可以让你不退出Python也可以完成一些操作,比如:
%cd
——更改当前的工作路径%edit
——新开一个编辑器并在其关闭后运行内部代码%env
——查看当前环境变量%pip install [pkgs]
——安装包- 当然,IPython的
In
和Out
都是真实的对象,是可以被调用的
3. Merging dictionaries
merged = { **dict1, **dict2 }
当key有重复时,前面的key会被覆盖掉
4. Emoji
直接在代码中用emoji,需要安装emoji模块:
pip install emoji
import emoji
result = emoji.emojize(‘Python is :thumbs_up:’)
result = emoji.demojize(‘Python is 👍’)
print(result)
# ‘Python is :thumbs_up:’
5. Pillow
通过Pillow模块来做一些图像显示、分析、编辑等一些操作。
安装:pip install Pillow
使用:
from PIL import Image
im = Image.open(image.jpg)
im.show()
6. set()
使用set()函数即可从列表(类列表的对象)中得到不重复的值
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
print (set(mylist))
# {1, 2, 3, 4, 5, 6}
7. Create a progress bar
用progress模块来创建进度条,
安装:pip install progress
使用:
from progress.bar import Bar
bar = Bar(‘Processing’, max=20)
for I in range(20):
# Do some work
bar.next()
bar.finish()
8. Web server
可以快速创建一个web服务器,来共享在内网中共享当前目录的资料或者测试站点
python -m http.server
9. Dates
通过python-dateutil模块,可以更好的来处理日期的问题,比如直接通过parse来自动从一段文字中提取时间信息:
from dateutil.parser import parse
logline = ‘INFO 2020-01-01T00:00:01 Happy new year, human.’
timestamp = parse(log_line, fuzzy=True)
print(timestamp)
# 2020-01-01 00:00:01
安装:pip install python-dateutil
10. Integer division
可以通过//来计算取整的除法了:
5 / 2 = 2.5
5 // 2 = 2
11. Charset detection
直接通过chardet模块来判断一个文件的字符类型:
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0
安装:pip install charted
Reference
其他的更多技巧,可以查看原文30 Python Best Practices, Tips, And Tricks