【问题标题】:Hot skip special character in txt file pythontxt文件python中的热跳过特殊字符
【发布时间】:2017-03-17 08:05:38
【问题描述】:

我在阅读 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

这是我的文件的样子: 有没有办法跳过那些“$”行?对不起那张照片,我不知道如何更好地附加它。

【问题讨论】:

  • 为什么不使用 np.genfromtxt?
  • 你试过if line.startswith('$')==False:吗?
  • @WhatsThePoint 是的,我尝试过,但失败了。
  • @user1753919 非常感谢它有效!我什至不知道像genfromtxt这样的阅读选项。

标签: python character skip


【解决方案1】:

感谢@user1753919,我找到了答案。如果有人对此仍然感兴趣,这里是工作代码:

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

【讨论】:

    【解决方案2】:

    genfromtxt 太过分了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 2012-08-07
      相关资源
      最近更新 更多