簡體   English   中英

如何在 python 中的文件的某些行中刪除多余的字符

[英]How to remove an extra character in some rows of a file in python

如果這個描述還不夠,我可以包含我的代碼示例,以進一步查看我的錯誤來自哪里。 目前,我有一個要導入的文件,如下所示...

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

在倒數第三行,最后一列的 0. 后面有一個逗號,看起來像“0.”。 因此,我得到了錯誤

Some errors were detected !
Line #7 (got 4 columns instead of 3)

對於我使用的代碼

%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()

也許有一種方法可以忽略該逗號並在前 3 列中明確讀取,或者有一種方法可以擺脫逗號,但我不確定。 任何建議都有幫助!

您可以通過以下方式刪除所有逗號並將其重新保存為新文件:

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.

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