【问题标题】:Aligning text columns of different size and content对齐不同大小和内容的文本列
【发布时间】:2016-11-12 01:53:17
【问题描述】:

past posting 中,我询问了Bash 中用于将文本列逐行对齐的命令。我很清楚,所需的任务(即,按行对齐不同大小和内容的文本列)比最初预期的要复杂得多,而且建议的 answer 虽然对于过去的发布是可以接受的,但在大多数情况下是不够的经验数据集。因此,我想向社区查询以下伪代码。具体来说,我想知道是否可以优化以下伪代码以及以何种方式优化。

假设一个文件包含 n 列字符串。某些字符串可能丢失,其他字符串可能重复。最长的列可能不是文件中列出的第一个列,而是参考列。必须保持此引用列的行顺序。

> cat file  # where n=3; first row contains column headers
CL1 CL2 CL3
foo foo bar
bar baz qux
baz qux
qux foo
    bar

伪代码尝试 1(完全不足):

Shuffle columns so that columns ordered by size (i.e., longest column is first in matrix)
Rownames = strings of first column (i.e., of longest column)
For rownames
  For (colname among columns 2:end)
    if (string in current cell == rowname) {keep string in location}
    if (string in current cell != rowname) {
      if (string in current cell == rowname of next row) {add row to bottom of table; move each string of current column one row down}
      if (string in current cell != rowname of next row) {add row to bottom of table; move each string of all other columns one row down}
    }

按大小排列列:

> cat file_columns_ordered_by_size
CL2 CL1 CL3
foo foo bar
baz bar qux
qux baz 
foo qux 
bar

寻求的输出:

> my_code_here file_columns_ordered_by_size
CL2 CL1 CL3
foo foo 
    bar bar
baz baz    
qux qux qux
foo
bar

【问题讨论】:

    标签: optimization pattern-matching pseudocode text-alignment


    【解决方案1】:

    编辑:呃,这不会产生你想要的输出。我想我不明白这个问题。无论如何,也许它会有所帮助。

    如果您不介意将整个表放入内存中,关联数组(散列)也可以。 (或者您可以使用树、地图、字典等。)每一列都有一个,将字符串(在该列的单元格中找到)映射到该字符串在该列中找到的次数。让我们在它们的列标题之后命名散列。啜饮后,它们看起来像这样:

    CL2 = {'foo':2, 'baz':1, 'bar':1, 'qux':1}
    CL1 = {'foo':1, 'baz':1, 'bar':1, 'qux':1}
    CL3 = {'bar':1, 'qux':1}
    
    # Store the columns in an array
    columnCounts = [CL2, CL1, CL3]
    

    然后编写一个产生输出的循环,在每次迭代时从关联数组中删除:

    while (columnCounts still has at least one non-empty hash) {
        key = the hash-key that is present in most (a plurality) of the hashes
        for each hash in columnCounts {
            if the key is in the hash {
                print key
                Decrement hash[key]
            }
            else {
                print whitespace
            }
        }
    
        print newline
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2013-08-27
      • 2020-09-06
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 2015-02-28
      相关资源
      最近更新 更多