txt文件python中的热跳过特殊字符

2024-05-23 16:45:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在阅读txt文件时遇到一些问题。我要做的是读取文件(大约360)并绘制一个图。除了在我的文件中有一个特殊的字符,比如“我们”时,一切都正常。当我的阅读功能发现那个字符时,它崩溃了。有没有办法跳过?我的代码:

import os
import matplotlib.pyplot as plt
import numpy as np

i = 10
j = 0
X = []
Y = []
Z = []
k = 0
A = np.zeros([360,719])

for i in range(10,360,10):
        X = []
        Y = []
        if len(str(i)) == 2:
            data = open(dir + '\\150317_ScPONd_0%s_radio.txt'%i, 'r')
        else:
            data = open(dir + '\\150317_ScPONd_%s_radio.txt'%i, 'r')
        z = data.readlines()
        data.close()
        for line in z:
            if not line.startswith('$'):
                data_2 = line.split('\t')
                X.append(data_2[0])
                Y.append(data_2[1])
        A[j,:] = X
        A[(j+1),:] = Y

我的文件是这样的: enter image description here 有没有办法跳过那些“$”行?对不起,那张照片,我不知道怎么贴得更好。在


Tags: 文件inimporttxtfordataifas
2条回答

genfromtxt是过度杀戮。在

np.loadtxt(file, comments='$')

我找到了答案。如果仍有人对此感兴趣,以下是工作代码:

for i in range(10,360,10):
        X = []
        Y = []
        if len(str(i)) == 2:
            data = np.genfromtxt(dir + '\\150317_ScPONd_0%s_radio.txt'%i,skip_header = 12)
        else:
            data = np.genfromtxt(dir + '\\150317_ScPONd_%s_radio.txt'%i,skip_header = 12)
        for line in data:
            X.append(line[0])
            Y.append(line[1])
        A[j,:] = X
        A[(j+1),:] = Y
        plt.plot(A[j,:],A[(j+1),:],label = '{} K'.format(i))
        plt.hold
        j = j+2

相关问题 更多 >