我对 Python 很陌生。我知道这已经被问过了,我很抱歉,但这种新情况的不同之处在于字符串之间的空格不相等。我有一个名为coord的文件,其中包含以下空格分隔的字符串:
1 C 6.00 0.000000000 1.342650315 0.000000000
2 C 6.00 0.000000000 -1.342650315 0.000000000
3 C 6.00 2.325538562 2.685300630 0.000000000
4 C 6.00 2.325538562 -2.685300630 0.000000000
5 C 6.00 4.651077125 1.342650315 0.000000000
6 C 6.00 4.651077125 -1.342650315 0.000000000
7 C 6.00 -2.325538562 2.685300630 0.000000000
8 C 6.00 -2.325538562 -2.685300630 0.000000000
9 C 6.00 -4.651077125 1.342650315 0.000000000
10 C 6.00 -4.651077125 -1.342650315 0.000000000
11 H 1.00 2.325538562 4.733763602 0.000000000
12 H 1.00 2.325538562 -4.733763602 0.000000000
13 H 1.00 -2.325538562 4.733763602 0.000000000
14 H 1.00 -2.325538562 -4.733763602 0.000000000
15 H 1.00 6.425098097 2.366881801 0.000000000
16 H 1.00 6.425098097 -2.366881801 0.000000000
17 H 1.00 -6.425098097 2.366881801 0.000000000
18 H 1.00 -6.425098097 -2.366881801 0.000000000
请注意第一列中每个字符串开头之前的空格。所以我尝试了以下将其转换为 csv 的顺序:
with open('coord') as infile, open('coordv', 'w') as outfile:
outfile.write(infile.read().replace(" ", ", "))
# Unneeded columns are deleted from the csv
input = open('coordv', 'rb')
output = open('coordcsvout', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
if row:
writer.writerow(row)
input.close()
output.close()
with open("coordcsvout","rb") as source:
rdr= csv.reader( source )
with open("coordbarray","wb") as result:
wtr= csv.writer(result)
for r in rdr:
wtr.writerow( (r[5], r[6], r[7]) )
当我运行脚本时,我在脚本的第一部分得到了coordv的以下内容,这当然是非常错误的:
, 1, C, , , 6.00, , 0.000000000, , 1.342650315, , 0.000000000
, 2, C, , , 6.00, , 0.000000000, -1.342650315, , 0.000000000
, 3, C, , , 6.00, , 2.325538562, , 2.685300630, , 0.000000000
, 4, C, , , 6.00, , 2.325538562, -2.685300630, , 0.000000000
, 5, C, , , 6.00, , 4.651077125, , 1.342650315, , 0.000000000
, 6, C, , , 6.00, , 4.651077125, -1.342650315, , 0.000000000
, 7, C, , , 6.00, -2.325538562, , 2.685300630, , 0.000000000
, 8, C, , , 6.00, -2.325538562, -2.685300630, , 0.000000000
, 9, C, , , 6.00, -4.651077125, , 1.342650315, , 0.000000000
, 10, C, , , 6.00, -4.651077125, -1.342650315, , 0.000000000
, 11, H, , , 1.00, , 2.325538562, , 4.733763602, , 0.000000000
, 12, H, , , 1.00, , 2.325538562, -4.733763602, , 0.000000000
, 13, H, , , 1.00, -2.325538562, , 4.733763602, , 0.000000000
, 14, H, , , 1.00, -2.325538562, -4.733763602, , 0.000000000
, 15, H, , , 1.00, , 6.425098097, , 2.366881801, , 0.000000000
, 16, H, , , 1.00, , 6.425098097, -2.366881801, , 0.000000000
, 17, H, , , 1.00, -6.425098097, , 2.366881801, , 0.000000000
, 18, H, , , 1.00, -6.425098097, -2.366881801, , 0.000000000
我在 .replace 中尝试了不同的可能性,但没有成功,到目前为止,我还没有找到任何关于如何做到这一点的信息来源。从此坐标文件中获取逗号分隔值的最佳方法是什么?我感兴趣的是使用python中的csv模块来选择4:6列,最后使用numpy导入它们,如下所示:
from numpy import genfromtxt
cocmatrix = genfromtxt('input', delimiter=',')
如果有人可以帮助我解决这个问题,我会很高兴。