标签: 转换

python实现json、ini、csv格式的文件转换

import json
from configparser import ConfigParser

# test.json
”’
[{“name”: “apple”, “price”: “10”, “amount”: “3”},
{“name”: “tesla”, “price”: “100000”, “amount”: “1”},
{“name”: “mac”, “price”: “3000”, “amount”: “2”},
{“name”: “lenovo”, “price”: “30000”, “amount”: “3”},
{“name”: “chicken”, “price”: “10”, “amount”: “3”}]
”’

# mysql.ini
”’
[DEFAULT]
a = test
[mysql]
default-character-set = utf8
[mysqld]
test1 = 200
datadir = /dbserver/data
port = 33060
character-set-server = utf8
sql_mode = NO_ENGINE_SUBSTRITUTION,STRICT_TRANS_TABLES
c = True
[test]
test1 = 100
”’

# sun.csv
”’
name,price,amount
apple,10,3
tesla,100000,1
mac,3000,2
lenovo,30000,3
chicken,10,3
”’

# file:json to csv
def json2csv(json_path, csv_path):
with open(json_path, ‘r’, encoding=’utf-8′) as f1:
with open(csv_path, ‘w’, newline=”) as f2:
ls = json.load(f1)
data = [list(ls[0].keys())]
for item in ls:
data.append(list(item.values()))
for line in data:
f2.write(‘,’.join(line) + ‘\n’)

# file:csv to json
def csv2json(json_path, csv_path):
ls = []
with open(csv_path, ‘r’, newline=”) as f1:
with open(json_path, ‘w’, encoding=’utf-8′) as f2:
for line in f1:
ls.append(line.replace(‘\n’, ”).split(‘,’))
# print(ls)
for i in range(1, len(ls)):
ls[i] = dict(zip(ls[0], ls[i]))
json.dump(ls[1:], f2, indent=4)
# 将Python数据类型转换成json格式,编码过程
# 默认是顺序存放,sort_keys是对字典元素按照key进行排序
# indent参数用语增加数据缩进,使文件更具有可读性

def ini2json(json_path, ini_path):
d = {}
cfg = ConfigParser()
cfg.read(ini_path)
for s in cfg.sections():
# print(s)
# print(cfg.items(s)) # 指定section,返回二元组
d[s] = dict(cfg.items(s))
with open(json_path, ‘w’) as f:
json.dump(d, f)

def json2ini(json_path, ini_path):
with open(json_path, ‘r’) as f1:
with open(ini_path, ‘w’) as f2:
dic = json.load(f1)
cfg = ConfigParser()
# print(ls)
for section, section_items in zip(dic.keys(), dic.values()):
cfg._write_section(f2, section, section_items.items(), delimiter=’=’)

if __name__ == ‘__main__’:
ini2json(‘./test2.json’, ‘./mysql.ini’)
json2ini(‘./test2.json’, ‘./sun.ini’)
json2csv(‘./test.json’, ‘./sun.csv’)
csv2json(‘./b.json’, ‘./sun.csv’)

Python 使用 OpenCC 实现中文简繁转换,Python 简繁体切换 zhconv

将输出以下结果:

支持中国大陆、台湾、香港异体字和地区习惯用词转换,如「里」「里」、「鼠标」「滑鼠」。
1
1.3.2 OpenCC 参数说明
  在上面的示例中,对 OpenCC 进行初始化时,会传入一个参数,其表示对应的转换模式。OpenCC 支持以下转换:

参数 说明
s2t 简体到繁体
t2s 繁体到简体
s2tw 简体到台湾繁体
tw2s 台湾繁体到简体
s2hk 简体到香港繁体
hk2s 香港繁体到简体
s2twp 简体到台湾繁体,并转换为台湾常用词汇
tw2sp 台湾繁体到简体,并转换为中国大陆常用词汇
tw2t 台湾繁体到繁体
t2tw 繁体到台湾繁体
hk2t 香港繁体到繁体
t2hk 繁体到香港繁体
t2jp 繁体到日本新字体
jp2t 日本新字体到繁体

参考
[1] OpenCC github

[2] Python – 常用库 – OpenCC(中文繁简体转换)
————————————————