首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建函数将字符串中的索引替换为列表中的索引,然后将这些值保存到HTML文件中。

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

Stack Overflow用户
提问于 2011-10-24 10:06:01
回答 1查看 166关注 0票数 0

好的,基本上我有一个csv文件,有不同的值。我希望csv中的每一行都需要创建一个新的html文件。csv行中的每个值都需要替换html中的values1 -7。我试着创建一个函数来处理这个问题,但是我不能让它改变html中的值。我可以手动更改该值,但我真的想知道如何使用函数进行更改。这不仅可以缩短编码量,还可以使其更加整洁和高效。

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-24 10:21:20

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

最快的修复方法可能是将字符串更改为函数的返回值。

代码语言:javascript
复制
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])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7870694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档