输入

输入

在 Ubuntu 上,如何重新格式化文本以适合宽度(最后一行除外),并在必要时添加空格?我能得到的最接近的是 with fmt --width=64,但这不会在单词之间添加空格。

输入

  • 摘自的片段,man zip删除了所有换行符并将双空格变成了单空格
Do not operate on files modified prior to the specified date, where mm is the month (00-12), dd is the day of the month (01-31), and yyyy is the year. The ISO 8601 date format yyyy-mm-dd is also accepted. For example:

fold --width=64输出

  • 断言,这是不可取的
Do not operate on files modified prior to the specified date, wh
ere mm is the month (00-12), dd is the day of the month (01-31),
 and yyyy is the year. The ISO 8601 date format yyyy-mm-dd is al
so accepted. For example:

fmt --width=65输出

  • 几乎完美,但还需要在单词之间添加空格
Do not operate on files modified prior to the specified date,
where mm is the month (00-12), dd is the day of the month
(01-31), and yyyy is the year. The ISO 8601 date format
yyyy-mm-dd is also accepted. For example:

想要的输出

  • 片段取自man zip
  • 在哪里插入双/三空格对我来说并不重要,只要线条符合指定的宽度并且单词或多或少均匀分布即可
Do not operate on files modified prior to  the  specified  date,
where  mm  is  the  month  (00-12),  dd  is the day of the month
(01-31), and  yyyy  is  the  year.   The  ISO 8601  date  format
yyyy-mm-dd is also accepted.  For example:

答案1

您可能需要考虑使用 nroff 来完成这项工作。以下是如何将其与名为 infile 的文件中的文本一起使用的示例:

$ 2>/dev/null nroff <(echo .pl 1 ; echo .ll 40) infile
Do  not  operate on files modified prior
to the specified date, where mm  is  the
month  (00‐12),  dd  is  the  day of the
month (01‐31), and yyyy is the year. The
ISO  8601 date format yyyy‐mm‐dd is also
accepted. For example:

.pl 1 roff 标记将页面高度设置为单行,从而禁用分页。

.ll 40 将行长度设置为 40 个字符。

nroff 是一种特殊的标记格式化实用程序,具有极好的定制可能性。

答案2

如果您不添加对本地化连字符的支持,您将不会对此感到高兴; 65 个字母太短了,尤其是当您的文本(与您使用的摘录不同)由较长的复合单词组成时。如果你试图证明一行有 10 个字母,德语和芬兰语使用者会讨厌你,因为它是介于 35 个字母和 40 个字母之间的两个单词。

无论如何,假设你不在乎关于排版,这并不难:Python 带来了textwrap模块,并且可以“分成行”最多65 个字符”,您所需要做的就是添加缺少的空格。

就像是脚本。 (不客气!)

下载脚本justify.py$PATH如果您不想指定脚本的完整路径,请将其放在您的 中的某个位置)和chmod 755 /path/to/justify.py。然后你就可以运行

echo 'Do not operate on files modified prior to the specified date, where mm is the month (00-12), dd is the day of the month (01-31), and yyyy is the year. The ISO 8601 date format yyyy-mm-dd is also accepted. For example:' \
     | /path/to/justify.py 65 \
     | cowsay -n

要得到

 ___________________________________________________________________ 
/ Do  not operate  on files modified  prior to the specified  date, \
| where  mm  is  the  month (00-12),  dd  is the  day  of the month |
| (01-31), and yyyy is the year. The ISO 8601 date format  yyyy-mm- |
\ dd is also accepted. For example:                                 /
 ------------------------------------------------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

我选择让它继续下去-;如果您不想这样做,请修改该wrapper = textwrap.Textwrapper(…行以包含break_on_hyphens=False.

相关内容