繁体   English   中英

如何在列表中添加文本文件中的某些项目?

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

我正在设置脚本,我需要从文本文件中获取一些值。

文本文件的体系结构为:

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

目的是获得以下输出:

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

以便将其写入我将创建的新文本文件中。

我已经试过了:

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

但这显然不起作用,但我没有找到一种转换事实的方法,以便在XYZ之后的所有行中添加列表。

尝试使用:

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

输出:

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

如果要整数:

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

输出:

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

使用正则表达式

例如:

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)

输出:

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

您可以遍历各行,并连接XYZ行之后的行,并在此过程中进行一些字符串处理:

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']

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

印刷品:

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

简短的正则表达式方法:

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)

输出:

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

暂无
暂无

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

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