简体   繁体   中英

How can I add in a list some items from a text file?

I'm setting up a script and I need to get some values from a text file.

The architecture of the text file is:

ABC;
XYZ
 1 2
 3 4;
DEF;
XYZ
 7 8
 9 10
 11 12;
GHI;

The objective is to obtain this output:

values_list = ['XYZ 1 2 3 4', 'XYZ 7 8 9 10 11 12']

in order to write it on a new text file that I'll create.

I've tried this:

my_file = open(file, 'r')
content = my_file.read()
line = my_file.readline()
if line.startwith('XYZ'):
   values_list.append(line)

but this obviously doesn't work but I don't find a way to translate the fact to add the list all the lines after XYZ .

Try using:

print(list(map(str.split, content.split(';')[1::2][:-1])))

Output:

[['XYZ', '1', '2', '3', '4'], ['XYZ', '7', '8', '9', '10', '11', '12']]

If you want integers:

print([i[:1] + list(map(int, i[1:])) for i in list(map(str.split, content.split(';')[1::2][:-1]))])

Output:

[['XYZ', 1, 2, 3, 4], ['XYZ', 7, 8, 9, 10, 11, 12]]

Using Regex

Ex:

import re
with open(filename) as infile:
    data = infile.read()

result = [" ".join(i.splitlines()).strip(";") for i in re.findall(r"([A-Z]+(?![;A-Z]).*?)[A-Z]+;", data)]   #Regex Help --> https://stackoverflow.com/a/21709242/532312
print(result)

Output:

['XYZ  1 2  3 4', 'XYZ  7 8  9 10  11 12']

You can iterate over the lines, and concatenate lines that follows the XYZ lines and do some string manipulation in the process:

In [48]: with open('file.txt') as f: 
    ...:     out = [] 
    ...:     text = '' 
    ...:     for line in f: 
    ...:         if line.startswith('XYZ'): 
    ...:             text = 'XYZ' 
    ...:         elif text.startswith('XYZ') and line.startswith(' '): 
    ...:             text += line.rstrip(';\n') 
    ...:         else: 
    ...:             if text: 
    ...:                 out.append(text) 
    ...:             text = '' 
    ...:                                                                                                                                                                                                    

In [49]: out                                                                                                                                                                                                
Out[49]: ['XYZ 1 2 3 4', 'XYZ 7 8 9 10 11 12']

Using re :

data = '''ABC;
XYZ
 1 2
 3 4;
DEF;
XYZ
 7 8
 9 10
 11 12;
GHI;'''

import re

out = [re.sub(r'\n|;', '', g, flags=re.M) for g in re.split(r'^\w+;', data, flags=re.M) if g.strip()]

print(out)

Prints:

['XYZ 1 2 3 4', 'XYZ 7 8 9 10 11 12']

Short regex approach:

import re

with open(file.txt') as f:
    content = f.read()
    repl_pat = re.compile(r'\s+')
    values = [repl_pat.sub(' ', s.group()) 
              for s in re.finditer(r'\bXYZ\s+[^;]+', content, re.M)]
    print(values)

The output:

['XYZ 1 2 3 4', 'XYZ 7 8 9 10 11 12']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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