我有一个文本文件,其中包含:
JavaScript 0
/AA 0
OpenAction 1
AcroForm 0
JBIG2Decode 0
RichMedia 0
Launch 0
Colors>2^24 0
uri 0
Run Code Online (Sandbox Code Playgroud)
我写了这段代码将文本文件转换为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")
Run Code Online (Sandbox Code Playgroud)
但是我在html文件中遇到的问题是在每一行中两列之间没有空格:
JavaScript 0
/AA 0
OpenAction 1
AcroForm 0
JBIG2Decode 0
RichMedia 0
Launch 0
Colors>2^24 0
uri 0
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能拥有相同的内容和文本文件中的两列
小智 9
只需将代码更改为包含<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")
Run Code Online (Sandbox Code Playgroud)
这是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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25017 次 |
| 最近记录: |