在Python中,如何基于以特定字符结尾的分隔符字符串拆分字符串列表?

2024-09-29 19:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多行的文本。你知道吗

我想根据以特定字符结尾的字符串来拆分它。你知道吗

例如: 我的文本包含以下数据

Hi
I'm here:
London
UK
USA
Where are you:
here 
there
what will you do:
something
somethin2

我要将此文本拆分为一个列表,其中分隔符作为以结尾的字符串

冒号-

在这种情况下,最终结果列表将是 [ Hi, London UK USA, here there, something somethin2 ] 在python中如何做到这一点?你知道吗

我知道我们可以用一个单独的字符或一些其他的字符串来分隔。但在这种情况下该怎么办呢?你知道吗


Tags: 字符串文本you列表here结尾情况hi
3条回答

下面是一个如何做到这一点的小例子。你知道吗

注意:比@Ajax1234的答案更容易理解,但效率要低得多。你知道吗

text = '''Hi
I'm here:
London
UK
USA
Where are you:
here 
there
what will you do:
something
somethin2'''

# add comma if there is ':' or else insert the line
output = [line.strip() if ':' not in line else ',' for line in text.split('\n')] 

# join the list on space
output = ' '.join(output) 

# split back into list on ',' and trim the white spaces
output = [item.strip() for item in output.split(',')]

print(output)

输出:

['Hi', 'London UK USA', 'here there', 'something somethin2']

可以使用正则表达式拆分:

>>> import re
>>> [s.strip().replace('\n',' ') for s in re.split(r'^.*:$',txt, flags=re.M)] 
['Hi', 'London UK USA', 'here there', 'something somethin2']

正则表达式^.*:$查找以:结尾的整行

Demo

re.splits分割该模式上的字符串并删除分隔线。然后在每个字符串块中用' '替换\n,就得到了所需的输出。你知道吗

您可以使用itertools.groupby

import itertools
data = [[a, list(b)] for a, b in itertools.groupby(content.split('\n'), key=lambda x:x.endswith(':'))]
final_result = [' '.join(b) for a, b in data if not a]

输出:

['Hi', 'London UK USA', 'here there', 'something somethin2']

相关问题 更多 >

    热门问题