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

Pac*_*ver 5 python regex json web.py python-2.7

假设文件系统中有一个文件,其中包含以$.

例如

<ul>
    <li>Name: $name01</li>
    <li>Age: $age01</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我能够通过正则表达式获取值:

#!/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
Run Code Online (Sandbox Code Playgroud)

这会将值打印到列表中:

[$name01, $age01]
Run Code Online (Sandbox Code Playgroud)

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

curl -H "Content-Type: application/json" -X POST -d '{"name":"Joe", "age":"25"}' http://localhost:8080/myservice
Run Code Online (Sandbox Code Playgroud)

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

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"]
Run Code Online (Sandbox Code Playgroud)

问题):

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

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

例如

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

将 $name01 替换为名称?

<ul>
    <li>Name: Joe</li>
    <li>Age: 25</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Pac*_*ver 1

关凯文,

感谢您的解决方案,但不幸的是它不起作用。

这是我的工作方式(数据是 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()
Run Code Online (Sandbox Code Playgroud)