=Start=
缘由:
整理总结一下最近在编码过程中遇到的一些Python知识点,方便以后快速参考、学习。(其实很多知识点之前都或多或少的整理过,但时间一长、很久没用之后就忘了,只能通过不断的使用、整理来加强记忆)
正文:
参考解答:
1、如何将文件中的内容(简单快速地)按行读入并放入set
set(line.strip() for line in open('filename.txt'))
即,如果没有什么复杂的判断、过滤条件,利用列表推导式即可快速实现(并不适合非常大的文件)。
- https://stackoverflow.com/questions/874017/python-load-words-from-file-into-a-set
- https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list
2、Python中的三元操作符
a = 1
b = 2
h = ""
print(h)
h = "变量1" if a>b else "变量2"
print(h)
is_fat = True
state = "fat" if is_fat else "not fat"
- https://www.cnblogs.com/mywood/p/7416893.html
- https://eastlakeside.gitbooks.io/interpy-zh/content/ternary_operators/ternary_operators.html
3、如何快速从URL中提取主机名等信息?
>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.netloc
'www.cwi.nl:80'
- https://pymotw.com/2/urlparse/
- https://docs.python.org/2/library/urlparse.html
- https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url
- https://stackoverflow.com/questions/9530950/parsing-hostname-and-port-from-string-or-url/17769986
4、如何判断某个IP是否为内网地址
方法一:借助 IPy 模块
方法二:Python 3提供了一个 ipaddress 的内置模块
方法三:用正则进行判断
方法四:用内置的unpack和socket模块进行判断
from struct import unpack
from socket import AF_INET, inet_pton
def lookup(ip):
f = unpack('!I',inet_pton(AF_INET,ip))[0]
private = (
[ 2130706432, 4278190080 ], # 127.0.0.0, 255.0.0.0 http://tools.ietf.org/html/rfc3330
[ 3232235520, 4294901760 ], # 192.168.0.0, 255.255.0.0 http://tools.ietf.org/html/rfc1918
[ 2886729728, 4293918720 ], # 172.16.0.0, 255.240.0.0 http://tools.ietf.org/html/rfc1918
[ 167772160, 4278190080 ], # 10.0.0.0, 255.0.0.0 http://tools.ietf.org/html/rfc1918
)
for net in private:
if (f & net[1]) == net[0]:
return True
return False
# example
print(lookup("127.0.0.1"))
print(lookup("192.168.10.1"))
print(lookup("10.10.10.10"))
print(lookup("172.17.255.255"))
# outputs True True True True
5、如何根据域名/主机名获取对应的IP
import socket
print socket.gethostbyname('stackexchange.com')
- https://stackoverflow.com/questions/34573322/read-a-list-of-hostnames-and-resolve-to-ip-addresses
- https://docs.python.org/2/library/socket.html#socket.gethostbyname
6、如何在解析域名的IP时使用自己设定的DNS服务器地址
from dns import resolver
res = resolver.Resolver()
res.nameservers = ['8.8.8.8']
answers = res.query('stackexchange.com')
for rdata in answers:
print (rdata.address)
- https://github.com/rthalley/dnspython
- https://stackoverflow.com/questions/34793061/socket-resolve-dns-with-specific-dns-server
7、Python中如何将 时:分:秒 的格式转换成 xx 秒?
# 方法一:借助 datetime 模块
>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0
# 方法二:累加计算
timestr = '00:04:23'
ftr = [3600,60,1]
sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
- https://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python
- https://stackoverflow.com/questions/6402812/how-to-convert-an-hmmss-time-string-to-seconds-in-python
8、Python中如何将 DD/MM/YYYY HH:MM:SS 等格式的日期字符串转换成 xx 秒的形式?
>>> import datetime
>>> import time
>>> s = "16/08/2013 09:51:43"
>>> d = datetime.datetime.strptime(s, "%d/%m/%Y %H:%M:%S")
>>> time.mktime(d.timetuple())
1376632303.0
- https://stackoverflow.com/questions/18269888/convert-datetime-format-into-seconds
- https://stackoverflow.com/questions/2775864/python-create-unix-timestamp-five-minutes-in-the-future/16307378#16307378
- https://docs.python.org/2/library/time.html#time.mktime
9、Python中如何将包含中文的json/dict进行格式化输出?
import json
your_json = '["foo", {"bar":["你好", null, 1.0, 2]}]' # json array string
parsed = json.loads(your_json) # type(parsed) == list
print(parsed)
# [u'foo', {u'bar': [u'\u4f60\u597d', None, 1.0, 2]}]
print(json.dumps(parsed, indent=4, ensure_ascii=False))
# [
# "foo",
# {
# "bar": [
# "\u4f60\u597d",
# null,
# 1.0,
# 2
# ]
# }
# ]
print(json.dumps(parsed, indent=4, ensure_ascii=False))
# [
# "foo",
# {
# "bar": [
# "你好",
# null,
# 1.0,
# 2
# ]
# }
# ]
- https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file
- https://docs.python.org/2/library/json.html#json.dumps
参考链接:
- 如上
=END=
《 “Python的一些小知识点_14” 》 有 3 条评论
Python 之路
https://laisky.com/p/python-road/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io
https://blog.laisky.com/p/unittest-mock/
https://blog.laisky.com/p/pbt-hypothesis/
一些你不知道的Python Tips
https://mp.weixin.qq.com/s/KTLRwzCM7lOvBF4IEGuBPg
`
这篇文章是我基于「Daily Python Tip」(@python_tip)这个Twitter账号里面的内容整理的一些关于Python的有意思的小例子,另外我也基于我的知识对其进行了扩展。
dict更新
隐式的字符串连接
print的妙用
__hello__和 __phello__
Python3打印emoji表情
`
https://realpython.com/python-print/
https://unicode.org/emoji/charts/full-emoji-list.html
Python:JSONPath基本语法和使用示例
https://blog.csdn.net/mouday/article/details/107928131
`
JSONPath语法元素和对应XPath元素的对比
…
# 安装
> pip install –upgrade jsonpath
# 使用示例
import jsonpath
ret = jsonpath.jsonpath(data, ‘$.store.book[*].author’) #所有书的作者
ret = jsonpath.jsonpath(data, ‘$..author’) #所有的作者
ret = jsonpath.jsonpath(data, ‘$.store..price’) #store里面所有东西的price
ret = jsonpath.jsonpath(data, ‘$..book[1].title’) #第二本书的title
`
JSONPath – XPath for JSON
https://goessner.net/articles/JsonPath/
JSONPath-简单入门
https://blog.csdn.net/luxideyao/article/details/77802389