简体   繁体   English

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

[英]How do I save specific text in an array from .txt file

I have a .txt file, where I want to save only following characters "N", "1.1" ,"XY", "N", "2.3" ,"xz" in an array.我有一个 .txt 文件,我只想在数组中保存以下字符 "N"、"1.1"、"XY"、"N"、"2.3"、"xz"。 The .txt file looks like this: .txt 文件如下所示:

[   TITLE

    N 1.1 XY
    N 2.3 XZ

]

Here is my code:这是我的代码:

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

The Output from my code is:我的代码的输出是:

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

The problem is the program also saves whitespace characters in an array which i dont want.问题是该程序还将空白字符保存在我不想要的数组中。

I would recommend the trim()-function with witch one you can remove whitespace from a string我会推荐带有可以从字符串中删除空格的女巫的 trim() 函数

Whitespace on both sides:两边的空格:

s = s.strip()

Whitespace on the right side:右侧空白:

s = s.rstrip()

Whitespace on the left side:左侧的空白:

s = s.lstrip()

Try this :尝试这个 :

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]

Output :输出

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

Try numpy.genfromtxt :尝试numpy.genfromtxt

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

Output:输出:

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

Or if you want list, add text_arr.tolist()或者如果你想要列表,添加text_arr.tolist()

You could check the return array before exiting:您可以在退出前检查返回数组:

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

The value None can then be used as a check condition in subsequent constructs:然后,值None可以用作后续构造中的检查条件:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM