Python的一些小知识点_14


=Start=

缘由:

整理总结一下最近在编码过程中遇到的一些Python知识点,方便以后快速参考、学习。(其实很多知识点之前都或多或少的整理过,但时间一长、很久没用之后就忘了,只能通过不断的使用、整理来加强记忆

正文:

参考解答:
1、如何将文件中的内容(简单快速地)按行读入并放入set
set(line.strip() for line in open('filename.txt'))

即,如果没有什么复杂的判断、过滤条件,利用列表推导式即可快速实现(并不适合非常大的文件)。

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"
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'
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')
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)
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(':')))])
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
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
# ]
# }
# ]
参考链接:
  • 如上

=END=


《“Python的一些小知识点_14”》 有 3 条评论

  1. 一些你不知道的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

  2. 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

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注