python中 yaml.dump 对dict dump成yaml文件时,给特定字符串保留(加上)单引号

以下例子来源于
https://www.cnblogs.com/saiminhou/p/13729119.html

python yaml dict对str类型加上单引号
源数据:

dict1 = {"user_id": 23026,
         "contact": [{"name": "phone",
                      "regexpr": "(^(0\d{2}-\d{8}(-\d{1,4})?)|(0\d{3}-\d{7,8}(-\d{1,4})?))|(^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})[ ]*$"}]
         }

python脚本:

import yaml
def quoted_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', u'%s' % data, style="'")
yaml.add_representer(str, quoted_presenter)
yaml.dump(dict1, sys.stdout, width=1200, default_flow_style=False, sort_keys=False)    

运行结果如下:str类型的都加上了单引号,数字没有

'user_id': 23026
'contact':
- 'name': 'phone'
  'regexpr': '(^(0\d{2}-\d{8}(-\d{1,4})?)|(0\d{3}-\d{7,8}(-\d{1,4})?))|(^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})[ ]*$'

 

python yaml dict对某个特定字符串加上单引号
源数据同上
python脚本:

import re
pattern = re.compile(r'regexpr|' + re.escape(
    '(^(0\d{2}-\d{8}(-\d{1,4})?)|(0\d{3}-\d{7,8}(-\d{1,4})?))|(^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})[ ]*$') + r'|user_id')
# pattern = re.compile(r'expr|user_id')    #对expr和user_id加上单引号
# pattern = re.compile(r'|')    #对所有的str类型加上单引号
yaml.add_implicit_resolver(None, pattern)
yaml.dump(dict1, sys.stdout, width=1200, default_flow_style=False, sort_keys=False)

运行结果如下:user_id、regexpr和后边那串正则表达式加上了单引号。expr本身是正则,用re.escapte就可以把这些字符自动转义,再用re.compile.

'user_id': 23026
contact:
- name: phone
  'regexpr': '(^(0\d{2}-\d{8}(-\d{1,4})?)|(0\d{3}-\d{7,8}(-\d{1,4})?))|(^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})[ ]*$'

 

posted @ 2022-10-12 11:23  panda4671  阅读(1036)  评论(0编辑  收藏  举报