我有一个看起来像这样的文本文件
P1 : Some data
P2 : blabla
P4 : whatever
F1 : something
F2 : something else
G6 : This entry continues
G6 : down here
这之后是一个空行,然后是一个看起来与上面相同的新记录(总共大约 100k)。我需要获取一个文本文件,其中每一行都包含由制表符分隔的 P2、p4 和 G6 条目。
这是我目前的情况
output = open('out.txt', 'w')
output.write("P1\tG6\n")
P1_ = False
G6_ = False
with open("data.txt", 'r') as data:
for line in data:
if line.startswith('P1 :'):
P1 = line[4:10]
P1_ = True
elif line.startswith('G6'):
G6 = line.lstrip('G6 :')
G6_ = True
else:
continue
if P1_ and G6_ :
output.write(year + "\t" + abstract)
year_ = False
abstract_ = False
output.close()
data.close()
我遇到的问题是有些记录没有我需要的所有条目,有些记录的 G6 分布在几行中。关于如何执行此操作的任何想法?
编辑:阅读您的所有回答后,我意识到我的问题有点含糊。我确实需要没有所有条目的记录。
请您参考如下方法:
正如其他人所建议的,您可以为每个数据 block 创建一个字典。当您点击空白行时,写入您的输出文件并清除字典。使用 defaultdict 可以更轻松地连接每个键的多个条目。
from collections import defaultdict
keep = ['P2', 'P4', 'G6']
tmp_dict = defaultdict(str)
# a function to handle formatting of output
def output_format(the_dict):
return '\t'.join([the_dict[k].rstrip() for k in keep]) + '\n'
with open('test.txt') as infile, open('output.txt', 'w') as outfile:
for line in infile:
# if there's non-whitespace text on this line
if line.strip():
k, v = line.split(' : ')
# store the data if the key is relevant,
# appending if the key has already been hit
if k in keep:
tmp_dict[k] += v.rstrip() + ' '
# when there's a blank line, write the data to
# the output file and clear the temporary dict
else:
outfile.write(output_format(tmp_dict))
tmp_dict = defaultdict(str)
# one last time, in case file doesn't end in newline
outfile.write(output_format(tmp_dict))
不确定我是否完全理解所需的输出。这将打印 P2 的值,然后打印 P4 的值,然后打印 G6 的所有值在一行上,每行之间有一个制表符。例如:
blabla whatever This entry continues down here
如果缺少一个元素,仍会打印制表符,因此如果缺少 P4,则会连续出现两个制表符。
但是输出是灵活的。例如,如果您想在过滤和合并 G6 后保留原始格式,那么您可以使用:
def output_format(the_dict):
output = ''
for k, v in the_dict.iteritems():
output += '{} : {}\n'.format(k, the_dict[k])
return output + '\n'
