【问题标题】:Reading input data to array(s) with multiple delimiters and headings将输入数据读取到具有多个分隔符和标题的数组
【发布时间】:2015-06-19 20:39:04
【问题描述】:

我正在尝试在 python 中编写一个解析器来读取输入文件,然后将结果组装成几个数组。

数据结构如下:

Some_numbers
1
5
6
some_vector
[-0.99612937 -0.08789929  0.        ]
[-0.99612937 -0.08789929  0.        ]
[ -9.99999987e-01   1.61260621e-04   0.00000000e+00]
Some_data
1239    #int    
671 
471 
851 
S4RS    #string
517 
18  
48  
912 
S4RS

目前我尝试过的方法有:

text_file = 'C:\AA\aa.txt'
lines = open(text_file).read().splitlines()
numbers = []
Vector = []
for line in lines:
    line = line.strip()
    if line.startswith('Some_numbers'):
        continue
        numbers.append(line)
    if line.startswith('some_vector'):
        continue
        Vector.append(line)

我遇到的问题是: 1) 有多个分隔符 2)尝试根据相关部分拆分数据

我还尝试使用 np.genfromtxt 以及无数小时在互联网上拖网。

非常感谢您的 cmets 和建议。

【问题讨论】:

    标签: python arrays string parsing delimiter


    【解决方案1】:

    我不确定是否有任何内置或库函数可以解决问题,但您的 for 循环中有一些明显的问题。

    首先,if 块内的 continue 之后的语句 - numbers.append(line)(或等效向量)。该语句将永远不会执行,因为 continue 会将控制权发送回 for 循环的开头,而 counter 变量会递增。

    其次,您没有根据 sections 阅读,这是您的输入包含的内容,尽管我会说您根本没有阅读任何内容。

    一个可以工作的示例代码(对于数字和向量是)-

    text_file = 'C:\AA\aa.txt'
    lines = open(text_file).read().splitlines()
    numbers = []
    Vector = []
    section = ''
    for line in lines:
        line = line.strip()
        if line.startswith('Some_numbers'):
            section = 'numbers'
            continue
        elif line.startswith('some_vector'):
            section = 'vectors'
            continue
        elif section == 'numbers':
            numbers.append(line) # or numbers.append(int(line)) , whichever you want
        elif section == 'vectors':
            Vector.append(line)
    

    请注意,以上代码仅用于数字和矢量,其他部分需要您自己编码。

    【讨论】:

      猜你喜欢
      • 2019-05-31
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多