在 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:
您可能需要考虑使用 nroff 来完成这项工作。以下是如何将其与名为 infile 的文件中的文本一起使用的示例:
.pl 1 roff 标记将页面高度设置为单行,从而禁用分页。
.ll 40 将行长度设置为 40 个字符。
nroff 是一种特殊的标记格式化实用程序,具有极好的定制可能性。
如果您不添加对本地连字符的支持,您将不会对此感到高兴;65 个字母太短了,尤其是当您的文本(与您使用的摘录不同)由较长的复合单词组成时。如果你试图证明一行有 10 个字母,德语和芬兰语人士会讨厌你,因为它是介于 35 个字母和 40 个字母之间的两个单词。
不管怎样,假设你不太关心排版,这并不难:Python 带来了这个
textwrap
模块,它可以“分成最多65 个字符的行”,你所需要做的就是添加缺少的空格。就像这个脚本一样。(不客气!)
下载脚本
justify.py
($PATH
如果您不想指定脚本的完整路径,请将其放在您的 中的某个位置)和chmod 755 /path/to/justify.py
。然后你就可以运行要得到
我选择让它继续下去
-
;如果您不想这样做,请修改该wrapper = textwrap.Textwrapper(…
行以包含break_on_hyphens=False
.