小编典典

合并两个文本文件-Ruby,Python,JavaScript,Java的最简单脚本方法?

java

我有两个文本文件,一个包含HTML,另一个包含URL链接:

文件1(HTML):

<li><a href="/article/"><button class="showarticle"/><span class="author">Thomas Friedman</span> - <span class="title">The World Is Flat</span></a></li>
<li><a href="/article/"><button class="showarticle"/><span class="author">Michael Dagleish</span> - <span class="title">Scotland In Wartime</span></a></li>
<li><a href="/article/"><button class="showarticle"/><span class="author">Dr. Raymond Kinsella</span> - <span class="title">Progress In Cancer Treatments</span></a></li>
...

文件2(URL链接):

thomas-friedman-the-world-is-flat
michael-dagleish-scotland-in-wartime
dr-raymond-kinsella-progress-in-cancer-treatments
...

我需要合并它们,以便将FILE 2中的段插入到FILE 1中的HTML中,如下所示:

输出:

<li><a href="/article/thomas-friedman-the-world-is-flat"><button class="showarticle"/><span class="author">Thomas Friedman</span> - <span class="title">The World Is Flat</span></a></li>
<li><a href="/article/michael-dagleish-scotland-in-wartime"><button class="showarticle"/><span class="author">Michael Dagleish</span> - <span class="title">Scotland In Wartime</span></a></li>
<li><a href="/article/dr-raymond-kinsella-progress-in-cancer-treatments"><button class="showarticle"/><span class="author">Dr. Raymond Kinsella</span> - <span class="title">Progress In Cancer Treatments</span></a></li>

什么是最好的方法?哪种语言最适合以最小的复杂度完成此任务?


阅读 221

收藏
2020-11-23

共1个答案

小编典典

您需要zip功能,该功能在大多数语言中都可用。目的是并行处理两个或多个数组。
在Ruby中将是这样的:

f1 = File.readlines('file1.txt')
f2 = File.readlines('file2.txt')

File.open('file3.txt','w') do |output_file|

    f1.zip(f2) do |a,b|
        output_file.puts a.sub('/article/','/article/'+b)
    end

end

要压缩更多,可以执行两个以上的数组 f1.zip(f2,f3,...) do |a,b,c,...|

2020-11-23