创建函数将字符串中的索引替换为列表中的索引,然后将这些值保存到HTML文件中。

2024-03-29 09:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有一个csv文件,有不同的值。我要从csv的每一行创建一个新的html文件。csv行中的每个值都需要替换html中的值1-7。我试图创建一个函数来处理这个问题,但是我无法让它更改html中的值。我可以手动更改值,但我真的很想知道如何使用函数进行更改。这不仅可以缩短编码量,而且可以使其更干净、更高效。在

import string
import csv

#functions


#open the southpark csv file
def opensouthparkFile(openFile1):
    southparklist = []
    for i in openFile1:
        i.strip()
       l = i.split(",")
       southparklist.append(l)
    return southparklist



useinput = raw_input("Enter the name of the file that you would like to open:")
openFile1 = (open(useinput, "rU"))
openFile2 = open("Marsh", "w")
openFile3 = open("Broflovski", "w")
openFile4 = open("Cartman", "w")
openFile5 = open("McCormick", "w")
openFile6 = open("Scotch", "w")


southfile = opensouthparkFile(openFile1)



html = """
<html>
<P CLASS="western", ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="font-size: 60pt">VALUE1</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="fontSsize: 36pt">VALUE2</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="font-size: 36pt"> VALUE3</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE4</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE5</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE6</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE7</FONT></P>
</html>
"""



#Function for replacing html files with southpark values

def replacehtml(html, somelist):
    html = html.replace("VALUE1", somelist[0])
    html = html.replace("VALUE2", somelist[1])
    html = html.replace("VALUE3", somelist[2])
    print somelist[1]




replacehtml(html, southfile[0])
replacehtml(html, southfile[1])





openFile2.write(html)

openFile2.close()

Tags: inmarginsizestyletophtmlopenclass
1条回答
网友
1楼 · 发布于 2024-03-29 09:39:13

Python通过一个称为“callbyobject”的方案传递参数。当您在replacehtml函数中重新分配字符串时,这不会更改原始的html字符串,因为字符串是不可变的类型。在

最快的解决方法可能是将字符串更改为函数的返回。在

def replacehtml(html, somelist):
    html = html.replace("VALUE1", somelist[0])
    html = html.replace("VALUE2", somelist[1])
    html = html.replace("VALUE3", somelist[2])
    print somelist[1]
    return html

html = replacehtml(html, southfile[0])

相关问题 更多 >