删除给定句子之前的文本
Deleting the text preceeding a given sentence
我正在处理一个包含大量生物数据的文件,我的输入文件看起来像,
Start
blah
blah
blah
blah
blah
5'UTR
IMPORTANT STRING
blah
blah
//
Start
blah
blah
blah
5'UTR
IMPORTANT STRING
blah
blah
blah
//
..... 等等这发生了大约 4k 次。现在的挑战是检查重要字符串是否包含 "NO information",是否删除整个段落(从开始到 //),如果没有将整个内容写入新文件。
我面临的问题是,当我这样做时,“5'UTR”未被识别为关键字,
for关键字行
我似乎也无法删除整个段落。
我如何在 python
中编写功能代码
以下脚本将创建一个新的 output.txt
文件,其中仅包含没有 NO information
行的块:
with open('file.txt', 'r') as f_input, open('output.txt', 'w') as f_output:
text = f_input.read()
blocks = re.findall(r"^(Start.*?^\/\/\n*)", text, re.M+re.S)
blocks = [block for block in blocks if re.search(r"5'UTR\n(?!NO information).*?\n", block, re.M+re.S)]
f_output.write("".join(blocks))
对于您的示例,output.txt
将与输入相同。它首先创建所有块的列表。然后它过滤掉任何具有 NO information
的块,然后将所有剩余的块写入一个新文件。
我不是读取整个文件并对其执行正则表达式,而是分块读取,一次一条记录,然后 yield
。产量是 Python 仅在需要时有效评估序列的方式。
def records(stream):
while stream:
lines = []
for line in stream:
lines.append(line)
if line.startswith('//'):
break
record = ''.join(lines)
yield record
for record in records(data):
if "5'UTR\nNO information" not in record:
output.write(record)
我正在处理一个包含大量生物数据的文件,我的输入文件看起来像,
Start
blah
blah
blah
blah
blah
5'UTR
IMPORTANT STRING
blah
blah
//
Start
blah
blah
blah
5'UTR
IMPORTANT STRING
blah
blah
blah
//
..... 等等这发生了大约 4k 次。现在的挑战是检查重要字符串是否包含 "NO information",是否删除整个段落(从开始到 //),如果没有将整个内容写入新文件。
我面临的问题是,当我这样做时,“5'UTR”未被识别为关键字, for关键字行 我似乎也无法删除整个段落。 我如何在 python
中编写功能代码以下脚本将创建一个新的 output.txt
文件,其中仅包含没有 NO information
行的块:
with open('file.txt', 'r') as f_input, open('output.txt', 'w') as f_output:
text = f_input.read()
blocks = re.findall(r"^(Start.*?^\/\/\n*)", text, re.M+re.S)
blocks = [block for block in blocks if re.search(r"5'UTR\n(?!NO information).*?\n", block, re.M+re.S)]
f_output.write("".join(blocks))
对于您的示例,output.txt
将与输入相同。它首先创建所有块的列表。然后它过滤掉任何具有 NO information
的块,然后将所有剩余的块写入一个新文件。
我不是读取整个文件并对其执行正则表达式,而是分块读取,一次一条记录,然后 yield
。产量是 Python 仅在需要时有效评估序列的方式。
def records(stream):
while stream:
lines = []
for line in stream:
lines.append(line)
if line.startswith('//'):
break
record = ''.join(lines)
yield record
for record in records(data):
if "5'UTR\nNO information" not in record:
output.write(record)