簡體   English   中英

編輯文本表格文件的有效方法,這樣每個單元格都在同一位置開始

[英]Efficient way to edit text tabular file so each cell starts at the same position

我有一個表格結構的文本文件,每行包含0到4個單詞,並以任意數量的空格分隔。

hello     world  this  is
     an   example  file
is   there a   good
way to    clean this
  your help is   
highly      appreciated

我的目標是以文件在行中相同位置開始的格式編輯此文件,例如:

hello    world        this     is
         an           example  file
is       there        a        good
way      to           clean    this
         your         help     is       
highly   appreciated

空格數是任意的。 我希望以空格開頭的行跳過第一個元素,但這並不嚴格。

我相信有很多方法可以做到這一點,我的偏好順序是:

  1. 在vim上使用一些巧妙的技巧
  2. 通過bash命令
  3. 在具有這種功能的文本編輯器上
  4. 通過腳本語言(可能是python)

由於這是數據准備/驗證過程的一部分,因此我不需要完美的方法。 畢竟,我將進行手動檢查。 我正在尋找一種可以完成80%至90%的工作的方法。

有人可以建議一種有效的方法嗎?

如果有用,示例文件在這里

這是一種使column尊重前導空格的方法:將前導空格更改為其他字符

sed 's/^ /_ /' file | column -t | sed 's/^_ /  /'
hello   world        this     is
        an           example  file
is      there        a        good
way     to           clean    this
        your         help     is
highly  appreciated

Python的re模塊.format()4.提供了一種很好的方法。

列寬基於文件中最長的非空白字符串的長度+ column_pad值。

您可以使用column_pad來改變實際的列寬。

如果您傳遞rename_file=True ,則會得到一個名為'cleaned_<filename> filename`的新文件。 否則,腳本將用清除的文件替換原始文件。

#!/usr/bin/env python
import re
import sys

def clean_columns(filename, rename_file=False, column_pad=4):
    if rename_file:
        cleaned_filename = 'cleaned_' + filename
    else:
        cleaned_filename = filename

    cleaned_text = ''

    with open(filename, 'r') as dirty_file:
        text = dirty_file.readlines()

    string_list = list(
        {string.strip()
                for line in text
                for string in line.strip().split(' ')})

    max_string_length = len(max(string_list, key=len))
    column_width = max_string_length + column_pad
    formatting_string = '{: <' + str(column_width) + '}'

    for line in text:
        line = re.sub(r'\s+',' ', line).split(' ')
        formatting = formatting_string * len(line)
        line = formatting.format(*line)
        cleaned_text += line + '\n'

    with open(cleaned_filename, 'w') as cleaned:
        cleaned.write(cleaned_text)


clean_columns('sample.txt', rename_file=True, column_pad=8)

輸出:

hello              world              this               is
                   an                 example            file
is                 there              a                  good
way                to                 clean              this
                   your               help               is
highly             appreciated

您可以使用https://github.com/junegunn/vim-easy-align插件來對齊各種分隔符

只需選擇行,然后按:

  • <CR> :映射到<Plug>(EasyAlign)
  • <CP> :實時預覽,可選
  • * :對齊所有定界符
  • <CD> :切換直到左對齊定界符
  • <CX>\\s\\@<=\\S\\+ :選擇空格后的非空格作為定界符

或使用以下命令: '<,'>EasyAlign */\\s\\@<=\\S\\+/dl

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM