簡體   English   中英

將多列文本文件排列為2列格式(VBA或Python)

[英]Arranging a multi-column text file into a 2-column format, VBA or Python

我有UTM x,y坐標的.dat文件,但x,y對沿5列排成一行。 我試圖將它們放入一個簡單的x,y列中。

由此:

10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35

對此:

10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

一位同事為此使用了VBA腳本,但是他在測試之后忘記保存它,現在我自己一個人。 我使用Python,並且幾乎沒有VBA經驗。

看起來您可以在雙倍空格處換行:

>>> data = '''10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35'''
>>> print(data.replace('  ', '\n'))
10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

或拆分值,然后遍歷x,y對:

>>> data = '''10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35'''
>>> xy = data.split()
>>> for x, y in zip(xy[0::2], xy[1::2]):
    print(x, y)
10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

在Python 3.4.3下,這對我來說似乎工作正常:

with \
    open('C:/Users/Gord/Desktop/thing.dat', 'r') as fin, \
    open('C:/Users/Gord/Desktop/thing.txt', 'w') as fout:
    for line in fin:
        items = line.split()
        for i in range(0, len(items), 2):
            print(items[i] + ' ' + items[i+1], file=fout)

暫無
暫無

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

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