将Python输出直接输出到文本文件和html

时间:2014-06-14 10:14:23

标签: python html text

我试图编写代码并在控制台,文本文件和html文件中输出,但是html文件的问题是所有输出都出现在一个像控制台线上出现的那样行:

def main():

import re, sys
from StringIO import StringIO
from os.path import basename,join

f2 = open('helloworld.html','w')
f1 = open("testing.txt",'w')

f= raw_input("\n Hello, use.\n \n PLease type in the name of the  press 'Enter': ") 

capture = StringIO()
save_stdout = sys.stdout
sys.stdout = capture


print f
x = "John"
g = "Peter"


if re.search(x,f) :
    print "It contains  John"
if re.search(g,f):
    print "It contains Peter"
if re.search(x,f) and re.search(g,f):
    print "It contains both persons"

sys.stdout = save_stdout    
print capture.getvalue()
template = """
<html>
    <head></head>
    <body>
        <p>%(text)s</p>
    </body>
</html>
"""

html_message = template %{"text":capture.getvalue()}


f2.write(html_message)
f2.close()

f1.write(capture.getvalue())
f1.close()

任何人都可以帮我这个吗?这是将输出的副本复制到文本文件和html文件???

的合适方法

1 个答案:

答案 0 :(得分:0)

您需要使用<br>替换html文件的换行符

这样的事情会起作用:

count=capture.getvalue().count('\n')-1 #you should do a count so that you don't add a newline at the end
html_message = template %{"text":capture.getvalue().replace('\n', "<br>\n", count)}

相反,你可以使用它来很好地格式化输出html文件:

template = """
<html>
    <head></head>
    <body>
        <p>%(text)s
        </p>
    </body>
</html>
"""

count=capture.getvalue().count('\n')-1
html_message = template %{"text":capture.getvalue().replace('\n', "<br>\n           ", count)[::-1].replace('\n', "", 1)[::-1]}
相关问题