用Python将文本文件转换为HTML文件

12

我有一个包含以下内容的文本文件:

JavaScript              0
/AA                     0
OpenAction              1
AcroForm                0
JBIG2Decode             0
RichMedia               0
Launch                  0
Colors>2^24             0
uri                     0

我编写了这段代码以将文本文件转换为HTML:

contents = open("C:\\Users\\Suleiman JK\\Desktop\\Static_hash\\test","r")
    with open("suleiman.html", "w") as e:
        for lines in contents.readlines():
            e.write(lines + "<br>\n")

但我在HTML文件中遇到的问题是每行两列之间没有空格:

JavaScript 0
/AA 0
OpenAction 1
AcroForm 0
JBIG2Decode 0
RichMedia 0
Launch 0
Colors>2^24 0
uri 0 

我该怎么做才能像在文本文件中一样拥有相同的内容和两列呢?


请发布所需的输出 - timgeb
HTML的内容应该与上面的文本文件相同,有两列。 - user3832061
5个回答

17

只需更改您的代码以包含<pre></pre>标签,以确保您的文本保持与原始文本文件中格式相同。

contents = open"C:\\Users\\Suleiman JK\\Desktop\\Static_hash\\test","r")
with open("suleiman.html", "w") as e:
    for lines in contents.readlines():
        e.write("<pre>" + lines + "</pre> <br>\n")

你的意思是编辑原始文本文件,使每列之间的空格更少吗? - 雨が好きな人
原始的文本文件中每行之间没有空格,但在 HTML 中每行之间有双倍空格。 - user3832061
从e.write()调用的第二个文字中删除您的<br>标记。 - 雨が好きな人

7
这是HTML -- 使用BeautifulSoup。
from bs4 import BeautifulSoup

soup = BeautifulSoup()
body = soup.new_tag('body')
soup.insert(0, body)
table = soup.new_tag('table')
body.insert(0, table)

with open('path/to/input/file.txt') as infile:
    for line in infile:
        row = soup.new_tag('tr')
        col1, col2 = line.split()
        for coltext in (col2, col1): # important that you reverse order
            col = soup.new_tag('td')
            col.string = coltext
            row.insert(0, col)
        table.insert(len(table.contents), row)

with open('path/to/output/file.html', 'w') as outfile:
    outfile.write(soup.prettify())

2

这是因为HTML解析器会将所有空格合并在一起。你可以有两种方法来解决这个问题(实际上可能还有更多种)。

一种方法是使用 "<pre>…</pre>" 标签将其标记为“预格式化文本”。

另一种方法是使用表格(这就是表格的作用):

<table>
  <tr><td>Javascript</td><td>0</td></tr>
  ...
</table>

手动输入相当繁琐,但很容易从脚本中生成。可以使用类似以下的代码:

contents = open("C:\\Users\\Suleiman JK\\Desktop\\Static_hash\\test","r")
with open("suleiman.html", "w") as e:
    e.write("<table>\n")   
    for lines in contents.readlines():
        e.write("<tr><td>%s</td><td>%s</td></tr>\n"%lines.split())
    e.write("</table>\n")

1
你可以使用独立的模板库,比如 makojinja。以下是一个使用 jinja 的示例:
from jinja2 import Template
c = '''<!doctype html>
<html>
<head>
    <title>My Title</title>
</head>
<body>
<table>
   <thead>
       <tr><th>Col 1</th><th>Col 2</th></tr>
   </thead>
   <tbody>
       {% for col1, col2 in lines %}
       <tr><td>{{ col 1}}</td><td>{{ col2 }}</td></tr>
       {% endfor %}
   </tbody>
</table>
</body>
</html>'''

t = Template(c)

lines = []

with open('yourfile.txt', 'r') as f:
    for line in f:
        lines.append(line.split())

with open('results.html', 'w') as f:
    f.write(t.render(lines=lines))

如果您无法安装 jinja,那么这里有一个替代方案:
header = '<!doctyle html><html><head><title>My Title</title></head><body>'
body = '<table><thead><tr><th>Col 1</th><th>Col 2</th></tr>'
footer = '</table></body></html>'

with open('input.txt', 'r') as input, open('output.html', 'w') as output:
   output.writeln(header)
   output.writeln(body)
   for line in input:
       col1, col2 = line.rstrip().split()
       output.write('<tr><td>{}</td><td>{}</td></tr>\n'.format(col1, col2))
   output.write(footer)

0

我已经添加了标题,逐行循环并将每行附加到 < tr > 和 < td > 标签上,它应该作为单个表格工作,无需使用这些标签(< tr >< /tr > 和 < td >< /td >[为了可读性而添加的空格])来处理 col1 和 col2。

日志:片段:

MUTHU PAGE

2019/08/19 19:59:25 MUTHUKUMAR_TIME_DATE,line: 118 INFO | Logger object created for: MUTHUKUMAR_APP_USER_SIGNUP_LOG 2019/08/19 19:59:25 MUTHUKUMAR_DB_USER_SIGN_UP,line: 48 INFO | ***** User SIGNUP page start ***** 2019/08/19 19:59:25 MUTHUKUMAR_DB_USER_SIGN_UP,line: 49 INFO | Enter first name: [只允许字母字符,最少3个字符,最多20个字符]

HTML 源页面:

'''

<?xml version="1.0" encoding="utf-8"?>
<body>
 <table>
  <p>
   MUTHU PAGE
  </p>
  <tr>
   <td>
    2019/08/19 19:59:25 MUTHUKUMAR_TIME_DATE,line: 118     INFO | Logger object created for: MUTHUKUMAR_APP_USER_SIGNUP_LOG
   </td>
  </tr>
  <tr>
   <td>
    2019/08/19 19:59:25 MUTHUKUMAR_DB_USER_SIGN_UP,line: 48     INFO | ***** User SIGNUP page start *****
   </td>
  </tr>
  <tr>
   <td>
    2019/08/19 19:59:25 MUTHUKUMAR_DB_USER_SIGN_UP,line: 49     INFO | Enter first name: [Alphabet character only allowed, minimum 3 character to maximum 20 chracter]

'''

代码:

from bs4 import BeautifulSoup

soup = BeautifulSoup(features='xml')
body = soup.new_tag('body')
soup.insert(0, body)
table = soup.new_tag('table')
body.insert(0, table)

with open('C:\\Users\xxxxx\\Documents\\Latest_24_may_2019\\New_27_jun_2019\\DB\\log\\input.txt') as infile:
    title_s = soup.new_tag('p')
    title_s.string = " MUTHU PAGE "
    table.insert(0, title_s)
    for line in infile:
        row = soup.new_tag('tr')
        col1 = list(line.split('\n'))
        col1 = [ each for each in col1 if each != '']
        for coltext in col1:
            col = soup.new_tag('td')
            col.string = coltext
            row.insert(0, col)
        table.insert(len(table.contents), row)

with open('C:\\Users\xxxx\\Documents\\Latest_24_may_2019\\New_27_jun_2019\\DB\\log\\output.html', 'w') as outfile:
    outfile.write(soup.prettify())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接