gpt4 book ai didi

Python:如何分割线合并一些线

转载 作者:行者123 更新时间:2023-11-28 21:43:38 25 4
gpt4 key购买 nike

我想逐行处理一个字符串,但我想启用多行支持。这是示例文本:

First line
Second line
{{{
these three lines
I want to process
together
}}}
Last Line

我希望多行从 {{{ 开始并在 }} 结束我以前是按以下方式逐行处理的:

lines = [l for l in text.splitlines()]
print lines

现在这段代码输出:

['First line', 'Second line', '{{{', 'these three lines', 'I want to process', 'together', '}}}', 'Last Line']

我想以某种方式使包含以下内容:

['First line', 'Second line', 'these three lines I want to process together', 'Last Line']

或者,更高级的例子

First Line
Second line
Third{{{line
fourth line
fifth}}}line
sixth line

在这种情况下,我希望行包含

['First Line', 'Second line', 'Third', 'line fourth line fifth', 'line', 'sixth line']

最佳答案

这是一个生成器,它将输入文件对象作为参数,一次生成一行。它应该在同一行接受尽可能多的 {{{}}} 但不测试不平衡的结构:

def merge_lines(fd):
concat = False
for line in fd:
while True:
#print (line)
if len(line.strip()) == 0: break
if not concat:
if ('{{{' in line):
deb, line = line.split('{{{', 1)
yield deb
concat = True
old = None
else:
yield line.strip('\r\n')
line = ""
if concat:
if ('}}}' in line):
deb, line = line.split('}}}', 1)
concat = False
if old:
yield old.strip() + ' ' + deb
else: yield deb
else:
if old:
old += ' ' + line.strip('\r\n')
else:
old = line.strip('\r\n')
line = ""

Python 3 中的示例:

>>> t = """First line
a{{{b}}}c{{{d
e
f}}}g{{{h
i}}}
j
k
"""
>>> for line in merge_lines(io.StringIO(t)): print(line)

First line
a
b
c
d e f
g
h i
j
k

关于Python:如何分割线合并一些线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com