Python工具库之三pypinyin和json、pickle
'''
json模块
json.dumps()
解析成字符串格式的json
json.loads()
把字符串格式的json序列化回去
写入 JSON 数据
with open('data.json', 'w') as f:
json.dump(data, f)
读取数据
with open('data.json', 'r') as f:
data = json.load(f)
pickle模块
和json的区别:
json是全语言通用的,pickle只能用在python
json适用的类型有限,pickle几乎所有的python对象都可以序列化
import pickle # 序列化和反序列化方法
obj = 213, "asdfs", 'fdsf', {'3we', 21}
print(obj)
a = pickle.dumps(obj) # 序列化对象,然后返回给变量
print(a)
aa = pickle.loads(a) # 变量的反序列化
print(aa)
with open("a.txt", "wb") as f:
pickle.dump(obj, f) # 序列化对象,然后写入文件
with open('a.txt', 'rb') as f:
s = pickle.load(f) # 文件反序列化
print(s)
javascript的序列化
JSON.stringify()
转换成json类型
JSON.parse()
反序列化回到javascript内置的类型
'''
from pypinyin import TONE2, lazy_pinyin
a = lazy_pinyin("会当凌绝顶,一览众山小") # 无音调
print(a) # ['hui', 'dang', 'ling', 'jue', 'ding', ',', 'yi', 'lan', 'zhong', 'shan', 'xiao']
b = lazy_pinyin("会当凌绝顶,一览众山小", style=TONE2) # 有音调
print(b) # ['hui4', 'da1ng', 'li2ng', 'jue2', 'di3ng', ',', 'yi1', 'la3n', 'zho4ng', 'sha1n', 'xia3o']
c = lazy_pinyin("园园,圆圆,媛媛,苑苑", style=TONE2)
print(c) # ['yua2n', 'yua2n', ',', 'yua2n', 'yua2n', ',', 'yua4n', 'yua4n', ',', 'yua4n', 'yua4n']