最简单的脚本方法来合并两个文本文件 - Ruby,Python,JavaScript,Java? [英] Easiest scripting method to merge two text files - Ruby, Python, JavaScript, Java?

查看:106
本文介绍了最简单的脚本方法来合并两个文本文件 - Ruby,Python,JavaScript,Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two text files, one containing HTML and the other containing URL slugs:

文件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 SLUGS):

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

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

I need to merge them so that the slugs in FILE 2 are inserted into the HTML in FILE 1 like this:

输出:

<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>

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

What's the best approach and which language would be most appropriate to accomplish this task with a minimum of complexity?

推荐答案

您需要zip-​​function,大多数语言都有。它的目的是并行处理两个或多个数组。

在Ruby中它将是这样的:

You need zip-function, which is available in most languages. It's purpose is parallel processing of two or more arrays.
In Ruby it will be something like this:

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,... |

For zipping more, than two arrays you can do f1.zip(f2,f3,...) do |a,b,c,...|

这篇关于最简单的脚本方法来合并两个文本文件 - Ruby,Python,JavaScript,Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆