[英]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
. 但这显然不起作用,但我没有找到一种转换事实的方法,以便在
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: 您可以遍历各行,并连接
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']
Using re
: 使用
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.