[英]How to remove an extra character in some rows of a file in python
If this description is not enough, I can include a sample of my code to further see where my error is coming from.如果这个描述还不够,我可以包含我的代码示例,以进一步查看我的错误来自哪里。 For the time being, I have a file that I am importing that looks like the following...
目前,我有一个要导入的文件,如下所示...
0.9,0.9,0.12
0.,0.75,0.16
0.7,0.75,0.24
0.7,0.75,0.32
0.5,0.,0.1
0.6,0.65,0.38
0.6,0.8,0.,
0.9,0.95,0.04
0.5,0.65,0.28
On the third to last row, there is a comma after the 0. of the last column, which looks like "0.,".在倒数第三行,最后一列的 0. 后面有一个逗号,看起来像“0.”。 Because of this, I get the error
因此,我得到了错误
Some errors were detected !
Line #7 (got 4 columns instead of 3)
for my code I use对于我使用的代码
%matplotlib notebook
import numpy as np #import python tools
import matplotlib.pyplot as plt
from numpy import genfromtxt
from mpl_toolkits.mplot3d import Axes3D
file = 'graph'
info = genfromtxt(file, delimiter=',')
beaming = info[:,0]
albedo = info[:,2]
diameter = info[:,1]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(diameter, albedo, beaming, c='r', marker='o')
ax.set_xlabel('diameter (km)')
ax.set_ylabel('albedo')
ax.set_zlabel('beaming parameter')
plt.show()
Maybe there is a way to ignore that comma and explicitly read in the first 3 columns or a way to get rid of the comma but i'm unsure.也许有一种方法可以忽略该逗号并在前 3 列中明确读取,或者有一种方法可以摆脱逗号,但我不确定。 Any suggestions help!
任何建议都有帮助!
You could remove all the commas and resave it as new file via:您可以通过以下方式删除所有逗号并将其重新保存为新文件:
with open("file.txt") as fi, open("out.txt", "w") as fo:
for line in fi:
line = line.strip()
if line[-1] == ",":
line = line[:-1]
fo.write(line + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.