0

我的问题是,如何在 Python 中获取两个不同的用户输入并将它们写入 HTML 文件,以便在打开文件时显示用户的输入?

我不想在浏览器中从 Python 打开 HTML 文件。我只想知道如何将 Python 输入传递给 HTML 文件,以及该输出必须如何准确地编码为 HTML。

这是代码:

name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")

with open('mypage.html', "r") as file_object:
    data = file_object.read()
    print(data)

我想获取名称输入和角色输入并将其传递给 HTML 文件,手动打开文件,然后将其显示为网页。当我打开文件时,输出看起来像这样:

<html>
<head>
<body>
<center>
<h1>
... Enter user name here... # in which i don't know how to print python user 
# input into the file
</h1>
</center>
<hr />
... Enter user input here...
<hr />
</body>
</html>
4

2 回答 2

1

用于format添加user input到 html 文件中

name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")
resut = """<html><head><body><center><h1>{UserName}</h1>
</center>
<hr />
{input}
<hr />
</body>
</html>""".format(UserName=name,input=persona)

print(resut)
于 2020-11-18T21:01:09.263 回答
0

这里的关键特性是在 HTML 文件中放置一些虚拟文本,以供替换:

我的页面.html:

<html>
<head>
<body>
<center>
<h1>
some_name
# input into the file
</h1>
</center>
<hr />
some_persona
<hr />
</body>
</html>

然后 Python 代码将确切地知道该怎么做:

import os

name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")

with open('mypage.html', 'rt') as file:
    with open('temp_mypage.html', 'wt') as new:
        for line in file:
            line = line.replace('some_name', name)
            line = line.replace('some_persona', persona)
            new.write(line)

os.remove('mypage.html')
os.rename('temp_mypage.html', 'mypage.html')
于 2020-11-18T21:20:37.967 回答