如何将.txt文件中的特定文本保存在数组中

时间:2019-12-02 06:52:13

标签: python python-3.x

我有一个.txt文件,我只想在数组中保存以下字符“ N”,“ 1.1”,“ XY”,“ N”,“ 2.3”,“ xz”。 .txt文件如下所示:

[   TITLE

    N 1.1 XY
    N 2.3 XZ

]

这是我的代码:

src = open("In.txt", "r")

def findOp (row):
    trig = False
    temp = ["", "", ""]
    i = 1
    n = 0
    for char in row:  
        i += 1
        if (char != '\t') & (char != ' ') & (char != '\n'):
            trig = True
            temp[n] += char
        else:
            if trig:
                n += 1
                trig = False

    return temp

for line in src.readlines():
print(findOp(line))

我的代码输出为:

['[', 'TITLE', '']
['', '', '']
['N', '1.1', 'XY']
['N', '2.3', 'XZ']
['', '', '']
[']', '', '']

问题在于程序还将空白字符保存在我不想要的数组中。

4 个答案:

答案 0 :(得分:1)

我会建议使用trim()函数,您可以从字符串中删除空格

两边的空白:

s = s.strip()

右侧的空格:

s = s.rstrip()

左侧的空白:

s = s.lstrip()

答案 1 :(得分:0)

尝试一下:

with open('In.txt', 'r') as f:
    lines = [i.strip() for i in f.readlines() if i.strip()][1:-1]
output = [[word for word in line.split() if word] for line in lines]

输出

[['N', '1.1', 'XY'], ['N', '2.3', 'XZ']]

答案 2 :(得分:0)

尝试numpy.genfromtxt

import numpy as np
text_arr = np.genfromtxt('In.txt', skip_header = 1, skip_footer = 1, dtype = str)
print(text_arr)

输出:

[['N' '1.1' 'XY']
 ['N' '2.3' 'XZ']]

或者,如果要列出,请添加text_arr.tolist()

答案 3 :(得分:0)

您可以在退出前检查返回数组:

def findOp(row):
    trig = False
    temp = ["", "", ""]
    i = 1
    n = 0
    for char in row:
        i += 1
        if (char != '\t') & (char != ' ') & (char != '\n'):
            trig = True
            temp[n] += char
        else:
            if trig:
                n += 1
                trig = False

    # Will return `temp` if all elements eval to True otherwise
    # it will return None        
    return temp if all(temp) else None

然后可以将值None用作后续构造中的检查条件:

for line in src.readlines():
    out = findOp(line)
    if out:
        print(out)

>> ['N', '1.1', 'XY']
>> ['N', '2.3', 'XZ']