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

2 投票
6 回答
6298 浏览
提问于 2025-04-16 08:41

我有两个文本文件,一个是包含HTML内容的,另一个是包含网址简写的:

文件 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 (网址简写):

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

我需要把这两个文件合并,也就是把文件 2 中的简写插入到文件 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>

请问有什么好的方法,使用哪种编程语言最简单,能完成这个任务呢?

6 个回答

2

这是一个 Ruby 的一行代码:

File.open("joined.txt","w") { |f| f.puts ['file1.txt', 'file2.txt'].map{ |s| IO.read(s) }}
2

这在任何编程语言中都很简单。下面是伪Python代码;我省略了lxml的部分,因为我没有访问权限,也记不太清楚语法。不过这些也不难。

with open(...) as htmls, open(...) as slugs, open(...) as output:
    for html, slug in zip(htmls, slugs):
        root = lxml.etree.fromstring(html)
        # do some fiddling with lxml to get the name

        slug = slug.split("-")[(len(name.split()):]
        # add in the extra child in lxml

        output.write(root.tostring())

有趣的特点:

  • 这个方法不会一次性读取整个文件,而是分块读取(实际上是逐行读取,但Python会进行缓存)。如果文件很大,这样做很有用,不过如果文件不大,这个特点可能就没什么意义了。

  • 根据HTML字符串的格式是否严格,lxml可能有点过于复杂。如果你能保证这些字符串都是一样的,并且格式都很好,使用简单的字符串操作可能会更简单。另一方面,lxml速度很快,而且提供了更多的灵活性。

6

你需要一个叫做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,...|

撰写回答