開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.6
#golang で dan さん提案の SION パーサ書いてみた。https://t.co/oG3crYhKrq
— mattn (@mattn_jp) 2018年7月11日
SION - is now Interchangeable [JavaScript] on @Qiita https://t.co/RZCB1ZLuGL
— Dan Kogai (@dankogai) 2018年7月12日
過去にSwiftの基本を触ってみてたけどだいぶ経ったし、Head First Swiftが出るみたいだからまたその時 Swift 触ってみよう(特に必要になることがそれまでなければ)と思ってたけど、面白そうだし基本的な型のことだけ知っておくのもいいかなぁと思って、Pythonで似たようなことをしてみることに。(とりあえずPythonのデータ型をSIONに変換するの一方通行のみ。しかも雑。>_<)
コード(Emacs)
sion.py
#!/usr/bin/env python3
def dump(obj, file):
t = type(obj)
if obj is None:
print('nil', file=file, end='')
elif t == bool:
if obj:
print('ture', file=file, end='')
else:
print('false', file=file, end='')
elif t in {int, float}:
print(obj, file=file, end='')
elif t == str:
print(f'"{obj}"', file=file, end='')
elif t == bytes:
print('.Data("{str(obj)[2:-1]}")', file=file, end='')
elif t in {list, tuple}:
print(f'[', file=file, end='')
if len(obj) > 0:
for o in obj[:-1]:
dump(o, file)
print(',', file=file, end='')
dump(obj[-1], file)
print(']', file=file, end='')
elif t == dict:
print('[', file=file, end='')
ks = list(obj.keys())
if len(ks) == 0:
print(':', file=file, end='')
elif len(ks) == 1:
dump(ks[0], file)
print(':', file=file, end='')
dump(obj[ks[0]], file)
else:
for k in ks[:-1]:
dump(k, file)
print(':', file=file, end='')
dump(obj[k], file)
print(',', file=file, end='')
dump(ks[-1], file)
print(':', file=file, end='')
dump(obj[ks[-1]], file)
print(']', file=file, end='')
if __name__ == '__main__':
obj = {
"nil": None,
"bool": True,
"int": -42,
"double": 42.195,
"string": "漢字、カタカナ、ひらがなの入ったstring😇",
"array": [None, True, 1, 1.0, "one", [1], {"one": 1.0}],
"dictionary": {
"nil": None,
"bool": False,
"int": 0,
"double": 0.0,
"string": "",
"array": [],
"object": {}
},
"url": "https://github.com/dankogai/"
}
with open('sample.sion', 'w') as f:
dump(obj, f)
入出力結果(Terminal, Jupyter(IPython))
$ ./sion.py $ cat sample.sion ["nil":nil,"bool":ture,"int":-42,"double":42.195,"string":"漢字、カタカナ、ひらがなの入ったstring😇","array":[nil,ture,1,1.0,"one",[1],["one":1.0]],"dictionary":["nil":nil,"bool":false,"int":0,"double":0.0,"string":"","array":[],"object":[:]],"url":"https://github.com/dankogai/"]$
Map(PythonのDictionary、JavaScriptのObject)が{a:1}ではなく[a:1]なとこが珍しい(?)っぽい。あと、空のMap(PythonのDictionary、JavaScriptのObjectの{})が[:]なところも。(こちらは、Pythonのtupleに近い印象。(長さが0の場合ではなく、長さが1の場合、tupleを('a')ではなく、('a',)と記述するところ。)
0 コメント:
コメントを投稿