Czs--从此蜕变

info函数的封装

大家在使用Python help或者info查看信息时,有时显得很不灵活,冗长并且全英文(可能对一些英文不太好的人而言不方便)。于是,我就封装了下面一个小方法,可以实现将模块或者函数的名称和doc string的中文解释对应上。这里的中文解释来源于有道词典的网络API数据抓取。

本代码推荐使用使用环境是Python3.5及以上版本,我测试的是Anaconda3-5.1.0-Windows-x86_64.exe版本;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import urllib.request

import http.client

import requests
import json
import re

from urllib import request,parse

def getTInfo(key):
# 通过抓包的方式获取的url,并不是浏览器上显示的url
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"

# 完整的headers
headers = {
"Accept" : "application/json, text/javascript, */*; q=0.01",
"X-Requested-With" : "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0",
"Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
}

formdata = {
"i":key,
"from":"auto",
"to":"auto",
"smartresult":"dict",
"client":"fanyideskweb",
"salt":"1511219405946",
"sign":"f8965f67a1d3eee8a69ddf8ccc5f582b",
"doctype":"json",
"version":"2.1",
"keyfrom":"fanyi.web",
"action":"FY_BY_REALTIME",
"typoResult":"false"
}
data=bytes(parse.urlencode(formdata),encoding='utf-8')
#利用Request将headers,dict,data整合成一个对象传入urlopen
req = request.Request(url,data,headers,method='POST')
response=request.urlopen(req)
info = response.read().decode('utf-8')

strRule = re.compile('"tgt":(.*?)}')
info2 = strRule.findall(info)
for i in info2:
i = i.replace('"',"")
return info2[0]

def info(object, spacing=15, collapse=0):
"""
Print methods and doc strings. Take module, class,
dictionary, or string.
"""
# 遍历一遍object对象,把里面的可以被调用的方法提取出来
methodList = [method for method in dir(object)
if callable(getattr(object, method))]

# 把要提取出来的方法以更好看的,多行变单行
#collapse可以控制打印的信息是否换行
#collapse = 1,并行
#collapse = 0,保持原来的显示
processFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s)

# 让左端打印的是方法名称,右端打印的是方法的doc名称
#print('\n'.join(["%s %s"%(str(method.ljust(spacing)),
# processFunc(str(getattr(object, method).__doc__)))

# for method in methodList]))

print('\n'.join(["%s %s"%(str(method.ljust(spacing)), processFunc(getTInfo(str(getattr(object, method).__doc__)))) for method in methodList]))



# 测试

import os

info(os.path)
🐶 您的支持将鼓励我继续创作 🐶