【问题标题】:How to write user input to HTML file?如何将用户输入写入 HTML 文件?
【发布时间】:2021-03-02 04:47:11
【问题描述】:

我的问题是,如何在 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>

【问题讨论】:

标签: python html python-3.x printing output


【解决方案1】:

使用formatuser 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)

【讨论】:

    【解决方案2】:

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

    mypage.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')
    

    【讨论】:

    • import os 有什么可能的替代品吗?比如import pathlib / from Path import pathlib??
    • 或者基本上是不需要import os模块的方式?
    • @carson,是的,我刚刚检查过,这似乎是可能的。我只是一直信任“os”模块,仅此而已。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2021-08-17
    • 2015-03-15
    相关资源
    最近更新 更多