简体   繁体   English

使用Python File IO在HTML文件中的特定位置添加文本

[英]Adding text at a specific place in an HTML file using Python File IO

I currently have an HTML file with words that run a script on click. 我目前有一个HTML文件,其中的单词可以在单击时运行脚本。 What I want to do on click is insert some text in line. 我想单击的内容是在行中插入一些文本。 Below is an example of what I want to have have happen. 以下是我想发生的事情的一个示例。

I want to go from this... 我想从这里...

 <!DOCTYPE html> <html> <body> <p> A whole bunch of words yada yada yada <a href="#" onclick="pythonScript(/wiki/Mercury_poisoning)" title="Mercury poisoning"> mercury poisoning </a> more words yada yada yada </p> </body> </html> 

To this... 为此...

  <!DOCTYPE html> <html> <body> <p> A whole bunch of words yada yada yada <a href="#" onclick="pythonScript(/wiki/Mercury_poisoning)" title="Mercury poisoning"> mercury poisoning </a> </p> <p> Text that comes from pythonScript </p> <p> more words yada yada yada </p> </body> </html> 

Note that the text coming from the python script is already in html format. 请注意,来自python脚本的文本已经是html格式。 How would I do this using Python File IO? 我将如何使用Python File IO做到这一点? If it is easier to do with another tool, what is the simplest tool to use for this problem? 如果更容易使用其他工具,那么用于此问题的最简单工具是什么?

I tried to use the write function but that overwrote the entire file. 我尝试使用write函数,但是覆盖了整个文件。 Then I tried writing in append mode but that still did not place the text where I wanted it. 然后,我尝试以附加模式编写文本,但是仍然没有将文本放置在所需的位置。 My third idea was to open the file in r+ mode and read until the word I clicked but I do not know how to ensure that the program will come to the correct string as opposed to the first instance of the string. 我的第三个想法是在r +模式下打开文件并读取,直到单击该单词为止,但我不知道如何确保程序将使用正确的字符串而不是字符串的第一个实例。

If you would like to do this with just the Python standard library, the following code snippet should work. 如果您只想使用Python标准库来执行此操作,则以下代码段应适用。

initial_code = '''
<!DOCTYPE html>
<html>

<body>
<p>
A whole bunch of words yada yada yada
<a href="#" onclick="pythonScript(/wiki/Mercury_poisoning)" title="Mercury poisoning">
 mercury poisoning
</a>
more words yada yada yada
</p>
</body>
</html>
'''

additional_code = '''
    <p> Text that comes from pythonScript
    </p>
'''

elements = initial_code.split("more words yada yada yada")

new_file = elements[0] + additional_code + elements [1]

However, this is not a great general-purpose solution. 但是,这不是一个很好的通用解决方案。 Depending on what you would like your script to do, it might be a better fit to use a templating library like Jinja2 to build your HTML page. 根据您希望脚本执行的操作,使用像Jinja2这样的模板库来构建HTML页面可能更合适。 Miguel Grinberg has a great tutorial on using Jinja2 in a Flask app, and introduces the concept of templates. Miguel Grinberg有一个很好的教程 ,介绍了如何在Flask应用程序中使用Jinja2,并介绍了模板的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM