[英]Arranging a multi-column text file into a 2-column format, VBA or Python
I have .dat files of UTM x,y coordinates but the x,y pairs are in rows along 5 columns. 我有UTM x,y坐标的.dat文件,但x,y对沿5列排成一行。 I am trying to get them into one simple x,y column. 我试图将它们放入一个简单的x,y列中。
From this: 由此:
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
To this: 对此:
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
A colleague had a VBA script working for this, but he forgot to save it after testing it, and now I'm on my own. 一位同事为此使用了VBA脚本,但是他在测试之后忘记保存它,现在我自己一个人。 I use Python and have very little VBA experience. 我使用Python,并且几乎没有VBA经验。
Looks like you can just break lines at the double spaces: 看起来您可以在双倍空格处换行:
>>> 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
Or splitting values and then going through x,y pairs: 或拆分值,然后遍历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
This seems to work fine for me under Python 3.4.3: 在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.