<p>让我们先谈一谈宽泛的术语,然后再具体说明。你知道吗</p>
<p>您的对象看起来像:</p>
<pre><code>object node {
name NAME_VAL;
phases PHASES_VAL;
nominal_voltage VOLTAGE_VAL;
}
</code></pre>
<p>您正试图从一个文件中写入这些对象到另一个空白文件中,只获取</p>
<pre><code>'SWING' in PHASES_VAL and NAME_VAL in [some list of nodes].
</code></pre>
<p>那么,让我们这样做:</p>
<pre><code>import itertools
def grouper(iterable, n, fillvalue=None)
'''from https://docs.python.org/3/library/itertools.html'''
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
with open('path/to/infile.txt') as inf, \
open('path/to/outfile.txt', 'w') as outf:
objects_in = grouper(inf, 6) # 5 lines of the object plus a newline
for obj in objects_in:
obj = list(obj) # let's look at them all at once
NAME_VAL = obj[1].strip().split()[1]
PHASES_VAL = obj[2].strip().split()[1]
VOLTAGE_VAL = obj[3].strip().split()[1]
if 'SWING' in PHASES_VAL and \
NAME_VAL in some_list_of_nodes:
outf.writelines(obj)
</code></pre>
<p>也就是说,如果这是您要反复做的事情,那么最好为此编写一个解析器。你知道吗</p>
<pre><code># node.py
class Node(dict):
'''simply inheriting from dict will handle almost everything,
but we will have to give it a classmethod to build from string'''
@classmethod
def from_string(cls, s):
kwargs = {}
reading = False
for line in s.splitlines():
if "}" in line:
return cls.__init__(**kwargs)
if reading:
key,val = line.strip().split()
kwargs[key]=val
if "{" in line:
reading = True
def __str__(self):
return "object node {\n" + \
"\n".join(" {} {}".format(item)\
for item in self.items()) + "\n}"
</code></pre>
<p>你知道吗</p>
<pre><code># parser.py
from node import Node
def parse(f):
tokens = []
token = []
parsing = False
for line in inf:
if line.startswith('object node {'):
parsing = True
if parsing:
token.append(line.strip())
if line.strip() == "}":
parsing = False
obj = Node("\n".join(token))
tokens.append[obj]
token = []
return tokens
</code></pre>
<p>你知道吗</p>
<pre><code># yourfile.py
import parser
with open('path/to/infile.txt') as infile, \
open('path/to/outfile.txt', 'w') as outfile:
for obj in parser.parse(infile):
if obj['name'] in some_node_names_list and \
'SWING' in obj['phases']:
outfile.write(str(obj))
</code></pre>