gpt4 book ai didi

html - 将我的 HTML 从一种形式转换为另一种形式

转载 作者:行者123 更新时间:2023-11-28 01:38:47 24 4
gpt4 key购买 nike

我刚刚在我的旧网页上浏览了一些糟糕的 HTML 标记。我注意到我的标记中有一些重复出现的错误。

我希望通过程序解决这些问题,但不确定哪种 API 或语言可以帮助我完成此任务。请问有人能帮帮我吗?

我的 HTML 是这种形式:

<td class="bulletPoint" align="right" valign="top" height="100%" width="100%">This is text</td>

我想替换成

<td class="bulletPoint" align="right" valign="top" height="100%" width="100%"><h2>This is text</h2></td>

我也有这种形式(class/colspan/href 可以变化):

<td class='original' colspan=4><a id='id12345' class='content' href='#note'">This is the text</a> 

并想将其转换为:

<font SIZE="3"  COLOR="#222222"  FACE="Verdana"  STYLE="background-color:#ffffff;font-weight: bold;"><h2>This is the text</h2></font>

当我有超过 1,000 个 .html 文件要执行此操作时,以编程方式执行此操作的最佳方法是什么?

谢谢

最佳答案

“以编程方式进行的最佳方式是什么”取决于您最了解哪些工具。我会用 python 和 beautifulsoup 来做。其他人可能会担保 sed 和正则表达式。查看我的方法:

创建两个单独的目录,一个包含原始 .html 文件的“副本”,另一个包含修改后的文件(不是原始文件的子目录)。

根据您的情况,一次运行或单独运行以下 python3 程序。您没有更改原始文件,您始终可以删除修改后的文件并重试。

您可以根据自己的需要更改 class_、colspan、href 等的选择,还可以创建多个程序,一个程序对应您可能遇到的每一种情况。

import os
from bs4 import BeautifulSoup

do = dir_with_original_files = '/path/to/your_original_files'
dm = dir_with_modified_files = '/path/to/your_modified_files'
for root, dirs, files in os.walk(do):
for f in files:
if f.endswith('~'): #you don't want to process backups
continue
original_file = os.path.join(root, f)
mf = f.split('.')
mf = ''.join(mf[:-1])+'_mod.'+mf[-1] # you can keep the same name
# if you omit the last two lines.
# They are in separate directories
# anyway. In that case, mf = f
modified_file = os.path.join(dm, mf)
with open(original_file, 'r') as orig_f, \
open(modified_file, 'w') as modi_f:
soup = BeautifulSoup(orig_f.read())
for t in soup.find_all('td', class_='bulletPoint'):
t.string.wrap(soup.new_tag('h2'))
# The following loop could belong to a separate python progam
# which would follow the same general structure.
for t in soup.find_all('td', class_='original'):
font = soup.new_tag('font')
font['size'] = '3'
font['color'] = '#222222'
font['face'] = 'Verdana'
font['style'] = 'background-color:#ffffff;font-weight: bold;'
t.string.wrap(soup.new_tag('h2')).wrap(font)
# This is where you create your new modified file.
modi_f.write(soup.prettify())

关于html - 将我的 HTML 从一种形式转换为另一种形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27172731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com