PythonClassChy/python27Class/unitTest/class04022020/regUse.py

67 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
=================================
Author: Flora Chen
Time: 2020/4/2 20:47
-_- -_- -_- -_- -_- -_- -_- -_-
=================================
"""
import re
from python27Class.unitTest.class04022020.handle_config import conf
test = {
'user': 'python',
'name' : 'flora',
'pwd' : 'lemonban',
'age' : 18
}
data = "{'user': '#user#', 'pwd': '#pwd#', 'name': '#name#', 'age': #age#}"
# 使用replace方法替换 (缺点:需要每一个单独进行替换,代码太多)
# 用replace方法需要多次替换 (缺点:每次只能替换一个数据,效率太低)
data = data.replace('#user#', test['user'])
data = data.replace('#pwd#', test['pwd'])
data = data.replace('#name#', test['name'])
data = data.replace('#age#', str(test['age']))
print(data)
# 使用正则替换
rule = re.search('#(.*?)#', data)
print(rule) # 输出结果:<re.Match object; span=(10, 16), match='#user#'>
# 获取匹配到的数据
key = rule.group()
print(key) # 输出结果:#user#
# 获取匹配规则中()里面的内容, 1表示第一个()里的内容
item = rule.group(1)
print(item) # 输出结果user
value = conf.get('REG', item)
data = data.replace(key, value)
print(data)
# 封装成方法
def replace_data(data):
while re.search('#(.*?)#', data):
rule = re.search('#(.*?)#', data)
# 获取匹配到的数据
key = rule.group()
# 获取匹配规则中()里面的内容, 1表示第一个()里的内容
item = rule.group(1)
# 用字典中的值来替换
value = str(test[item])
# 用配置文件中的值来替换
# value = conf.get('REG', item)
data = data.replace(key, value)
return data
res = replace_data(data)
print('结果:', res)