【问题标题】:Translate html snippet from A to B将html片段从A翻译成B
【发布时间】:2019-10-14 22:03:41
【问题描述】:

我正在使用 microsoft word,过滤 html 来创建网站内容。有充分的理由(文字更改图像),我想在我的网站上指定正确的图像路径。每个图像都有一个关联的超链接(放置在 word 文件中)到正确的图像路径。 Word 似乎无法为图像源设置真实文件名,而是更愿意将图像放置在具有不同图像名称的单独目录中。该死的windoze和word,太有用了,无法避免。

我需要一个 bash 脚本(不确定是否合适的工具)来转换文件 $1 中的字符串:

src="._files/." 到 src="与之前的 href="/SecureOffice_Images/."" 匹配 其中 . 是通配符

示例输入

<p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;
text-align:center'><span lang=EN-CA><a
href="/SecureOffice_Images/PuTTY_Login_Prompt.jpg"><span style='color:windowtext;
text-decoration:none'><img border=0 width=391 height=80 id="Picture 2"
src="Tools_files/image002.jpg"></span></a></span></p>

示例输出:

<p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;
text-align:center'><span lang=EN-CA><a
href="/SecureOffice_Images/PuTTY_Login_Prompt.jpg"><span style='color:windowtext;
text-decoration:none'><img border=0 width=391 height=80 id="Picture 2"
src="/SecureOffice_Images/PuTTY_Login_Prompt.jpg"></span></a></span></p>

src="Tools_files/image002.jpg" 已替换为 src="/SecureOffice_Images/PuTTY_Login_Prompt.jpg"

换句话说,“src=”值被&lt;p&gt; &lt;/p&gt;标签之间的先前“href=”值替换

有人有工具/代码建议吗?脚本将在 linux 上运行。

谢谢; 比尔

【问题讨论】:

  • 基本上,您的任务要求解析器生成树表示,该树表示带有允许修改层次结构的 API。一种方法是从 html 构建 DOM 并使用 JS。另一个想法是使用像 xmllintxmlstarlet 这样的 linter 将 html 转换为语法上有效的 xml(即 xhtml),然后运行 ​​xslt 样式表以根据您的规范转换 html。快速而肮脏(最终非常痛苦)的路径将带您进入正则表达式领域。最佳选择取决于您的技术堆栈、技能以及这是否是一次性任务。
  • 当您在硬盘驱动器的根路径中有网站图像时,Word 会正确处理指向路径的超链接。例如,突出显示某些文本并创建超链接会得到此directory/screenshot.jpg,其中 directory 是实际网站文件结构根目录的路径。
  • 问题不是超链接路径(我可以正确设置),它是 img src= path
  • 它是一个每次更新的站点,不是一次任务,许多受影响的文件。

标签: html regex text


【解决方案1】:

感谢@collapsar

您让我认为我的图像链接方法需要太多工作/复杂性,因为链接是一个单独的元素,需要构建元素树并进行元素间多行搜索 + 替换,所以我希望简化问题(创建我自己的方法)。

新方法:不要使用链接字段来指定真实图像路径,使用“alt=”字段,它将与“src=”字段出现在同一行,而“href=”可能不会(引入复杂性) .

新输入:

<p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;
text-align:center'><span lang=EN-CA><img border=0 width=429 height=409
id="Picture 19" src="Tools_files/image001.jpg"
alt="/SecureOffice_Images/PuTTY_Login.jpg"></span></p>

新输出:

<p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;
text-align:center'><span lang=EN-CA><img border=0 width=429 height=409
id="Picture 19" 
src="/SecureOffice_Images/PuTTY_Login.jpg"></span></p>

翻译算法:

perl -pi -e 's|src=".*?"||g' $1
sed -i 's/alt=/src=/g' $1

我尝试(更喜欢) sed 而不是 perl,但无法绕过贪婪: sed -i 's/src=".*?"//g' $1(Q - 可以使用 sed 吗?)

所以现在,我有一种方法可以自动从 MS Word 过滤的 html 转到我的网站需要的内容。现在,手动运行翻译脚本。最终,将它与我的预渲染自动 TOC 和弹出窗口创建脚本集成。

仅供参考:这是网站:www.rossco.org

问候; 比尔

【讨论】:

    猜你喜欢
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多