【问题标题】:Bash Script for Concatenating Broken Dashed Words用于连接破折号的 Bash 脚本
【发布时间】:2021-02-28 18:37:55
【问题描述】:

我已经抓取了大量 (10GB) 的 PDF 并将它们转换为文本文件,但是由于原始 PDF 的格式,存在一个问题:

许多跨行的单词中都有一个破折号,人为地将单词分开,如下所示:

您可以看到这是因为原始 PDF 文件有中断:

.txt 文件中“加入”与此模式匹配的每个单词实例的最简洁和最快的方法是什么?

也许某种正则表达式搜索,例如某种类型的[a-z]\-\s \w(单词字符后跟破折号后跟空格)会起作用吗? 或者某种sed 替换会更好吗?

目前,我正在尝试使用 sed 正则表达式,但我不确定如何翻译它以使用捕获组替换所选文本:

sed -n '\%\w\- [a-z]%p' Filename.txt

我的输入文本如下所示:

The dog rolled down the st- eep hill and pl- ayed outside.

输出将是:

The dog rolled down the steep hill and played outside.

理想情况下,该表达式也适用于由换行符分割的单词,如下所示:

The rule which provided for the consid-
eration of the resolution, was agreed to earlier by a

到这里:

The rule which provided for the consideration 
of the resolution, was agreed to earlier by a

【问题讨论】:

  • 可能使用 2 个捕获组并仅使用这 2 个组进行替换。 ([a-z])-\r?\n(\w)regex101.com/r/IoGA1x/1
  • 这似乎可行,如何实现捕获替换? (我在上面添加了我的尝试,仅供参考)。
  • 刚刚将输入/输出文本添加到上述问题中。

标签: regex string bash sed data-cleaning


【解决方案1】:

在 sed 中很简单:

sed -e ':a' -e '/-$/{N;s/-\n//;ba
}' -e 's/- //g' filename

这大致翻译为“如果该行以破折号结尾,请同时阅读下一行(这样您就有一行中间有回车符),然后删除破折号和回车符,然后循环返回以防万一新行也以破折号结尾。然后删除 - " 的所有实例。

【讨论】:

  • 这太棒了!它完美地满足了第二个用例。你会如何建议调整它来修复内嵌的分手,比如第一句话?
  • @HarryCramer:对不起,我在您编辑问题之前发布了,我没有注意到屏幕截图中的内部中断。我会编辑。
【解决方案2】:

您只需添加反斜杠括号(或使用-r-E 选项,以取消在捕获括号之前放置反斜杠的要求)并使用\1 调用匹配的文本作为第一个捕获括号,\2 第二个等。

sed 's/\(\w\)\- \([a-z]\)/\1\2/g' Filename.txt

\w 转义不是标准的sed,但如果它适合您,请随意使用。否则,很容易替换为[A-Za-z0-9_@] 或其他任何你想称之为“单词字符”的东西。

我猜不是所有的匹配都会是连字符的单词,所以可能会通过拼写检查器或其他工具运行结果以验证结果是否是英文单词。 (不过,我可能会为此改用 Python 等功能更强大的脚本语言。)

【讨论】:

    【解决方案3】:

    您可以使用此gnu-awk 代码:

    cat file
    
    The dog rolled down the st- eep hill and pl- ayed outside.
    The rule which provided for the consid-
    eration of the resolution, was agreed to earlier by a
    

    然后像这样使用 awk:

    awk 'p != "" {
       w = $1
       $1 = ""
       sub(/^[[:blank:]]+/, ORS)
       $0 = p w $0
       p = ""
    }
    {
       $0 = gensub(/([_[:alnum:]])-[[:blank:]]+([_[:alnum:]])/, "\\1\\2", "g")
    }
    /-$/ {
       p = $0
       sub(/-$/, "", p)
    }
    p == ""' file
    
    The dog rolled down the steep hill and played outside.
    The rule which provided for the consideration
    of the resolution, was agreed to earlier by a
    

    如果您可以考虑perl,那么这也可能适合您:

    然后使用:

    perl -0777 -pe 's/(\w)-\h+(\w)/$1$2/g; s/(\w)-\R(\w+)\s+/$1$2\n/g' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 2012-05-10
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多