如何使用 Python 将 JSON 中的值替换为 RegEx 在文件中找到的值?

How to replace values from JSON with those found by RegEx in a file using Python?

假设文件系统中有一个文件,其中包含以 $ 为前缀的值。

例如

<ul>
    <li>Name: $name01</li>
    <li>Age: $age01</li>
</ul>

我能够通过 RegEx 获取值:

#!/usr/bin/env python 
import re

with open("person.html", "r") as html_file:
    data=html_file.read()   
list_of_strings = re.findall(r'$[A-Za-z]+[A-Za-z0-9]*', data)
print list_of_strings

这会将值打印到列表中:

[$name01, $age01]

现在,我向我的 web.py 服务器发送一个 JSON 示例负载,如下所示:

curl -H "Content-Type: application/json" -X POST -d '{"name":"Joe", "age":"25"}' http://localhost:8080/myservice

我能够像这样获得这些值:

import re
import web
import json

urls = (
    '/myservice', 'Index',
)

class Index:
    def POST(self):
        data = json.loads(web.data())

        # Obtain JSON values based on specific keys
        name = data["name"]
        age = data["age"]

问题:

  1. 如何从有效负载中迭代获取 JSON 值并将它们放入列表中(而不是通过键名手动获取它们)?

  2. 获得此列表后,如何用列表中的 JSON 值替换 HTML 文件中的值?

例如

如何在 HTML 文件中手动插入这些项目(根据上面定义的 RegEx exp):

将 $name01 替换为名称?

<ul>
    <li>Name: Joe</li>
    <li>Age: 25</li>
</ul>

这是我的方法(也许这是更好的方法):

import re
import json

html = """
<ul>
    <li>Name: $name01</li>
    <li>Age: $age01</li>
</ul>"""

JSON = '{"name01":"Joe", "age01":"25"}'
data = json.loads(JSON)

html = re.sub(r'$(\w+)', lambda m: data[m.group(1)], html)

print(html)

输出:

<ul>
    <li>Name: Joe</li>
    <li>Age: 25</li>
</ul>

顺便说一下,我更喜欢使用像 Jinja2 这样的模板。由于我不知道web.py,所以我不能举个例子。但是我找到了文档:http://webpy.org/docs/0.3/templetor

关凯文,

感谢您的解决方案,但不幸的是它没有奏效。

这是我如何让它工作的(数据是 json 内容):

def replace_all(output_file, data):
    homedir = os.path.expanduser("~")
    contracts_dir = homedir + "/tmp"
    with open(output_file, "r") as my_file:
        contents = my_file.read()
    destination_file = contracts_dir + "/" + data["filename"]
    fp = open(destination_file, "w")
    for key, value in data.iteritems():
        contents = contents.replace("$" + str(key), value)
    fp.write(contents)
    fp.close()