在编写文本文件时控制文本对齐方式。

huangapple go评论89阅读模式
英文:

Controlling text alignment when writing a text file

问题

我需要创建文本文件,并且希望能够使用Go语言控制文本是左对齐还是右对齐。我找到了tab writer,但我不想使用列。文本需要自由流动。有什么建议吗?

英文:

I need to create text files and have the ability to control if the text is left or right justified using Go.
I found tab writer but I don't want columns. The text needs to flow freely.
Any suggestions?

答案1

得分: 1

你在ASCII文本文件中的格式化选项非常有限。没有ASCII控制字符可以指定文本块以特定方式对齐。你要么依赖文本查看器来解释自定义语法作为格式化(参见Markdown格式),要么在每一行上添加空格来明确创建所需的格式。

对于后者,你可以在每一行前面插入空格来模拟对齐。为此,你需要选择每行的固定字符数(例如40个字符)作为格式化的基础。请注意,这个最大行宽不一定与用户所使用的文本查看应用程序中的屏幕大小相匹配。

左对齐算法基本上是一个自动换行算法。请参考https://stackoverflow.com/questions/17586/best-word-wrap-algorithm。

右对齐算法也是自动换行,但有一个中间步骤:让自动换行函数首先返回你的文本拆分为自动换行的行,然后在每一行的开头填充与剩余字符数相等的空格数,以适应最大行宽。

假设你的源文本是"There is no justification for this statement!",最大行宽为15个字符。左对齐算法将输出:

There is no
justification
for this
statement! 

...而右对齐算法将输出:

    There is no
  justification
       for this
     statement! 

如果你想更改最大行宽,那么你需要再次运行算法,以便使用新的最大行宽重新排列文本。

英文:

You are very limited in the kinds of formatting you can perform within an ASCII text file. There are no ASCII control characters to say that a block of text will be justified in a certain way. You are either relying on a text viewer to interpret a custom syntax as formatting (see the Markdown format) or you are adding spaces to explicitly create the formatting you want on each line.

For the latter, you can insert spaces in front of each line to simulate justification. To do this, you'll need to pick a fixed number of characters per line (e.g. 40 characters) as the basis of your formatting. Note that this maximum line width won't necessarily match the size of the screen in whatever text viewing app your user has.

The left-justification algorithm is basically a word-wrapping algorithm. See https://stackoverflow.com/questions/17586/best-word-wrap-algorithm for that.

The right-justification algorithm is word-wrapping again, but with an intermediate step: Have the word-wrapping function return your text split into word-wrapped lines first. And then pad the start of each line with a count of spaces equal to the count of characters you had remaining to fit inside of the maximum line width.

So say your source text is "There is no justification for this statement!" and your maximum line width is 15 characters. The left-justification algorithm will output this:

There is no
justification
for this
statement! 

...and the right-justification algorithm will output this:

    There is no
  justification
       for this
     statement! 

If you want to change the maximum line width, then you need to run the algorithm again to reflow the text with a new maximum line width.

huangapple
  • 本文由 发表于 2022年10月24日 07:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/74175567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定