遍历字符串列表中的元素,并在满足条件的情况下合并

时间:2020-03-24 21:18:52

标签: python list python-regex

我正在尝试编写代码,该代码将遍历字符串列表中的元素,并将以小写字母开头的元素与前一个元素组合在一起。例如,给出以下列表:

test_list = ['Example','This is a sample','sentence','created to illustrate','the problem.','End of example']

我想列出以下列表:

test_list = ['Example','This is a sample sentence created to illustrate the problem.','End of example']

这是我尝试过的代码(不起作用):

for i in range(len(test_list)):
    if test_list[i].islower():
        test_list[i-1:i] = [' '.join(test_list[i-1:i])]

我认为尝试递归使用此联接可能会出现问题。有人可以推荐一种解决方法吗?作为背景,我之所以需要这样做,是因为我将许多不同大小的PDF文档转换为文本,然后将其拆分为多个段落以使用每个文档上的re.split('\n\s*\n',document)提取特定项目。它适用于大多数文档,但是由于某种原因,其中某些文档在每个其他单词之后或在与段落末尾不对应的随机位置中都有一个“ \ n \ n”,因此,我尝试将它们组合以实现更合理的段落列表。另一方面,如果有人对如何将提取的原始文本拆分成段落有更好的了解,那也将是很棒的。预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用:

output = [test_list[0]]
for a, b in zip(test_list, test_list[1:]):
    if b[0].islower():
        output[-1]  = f'{output[-1]} {b}'
    else:
        output.append(b)
output

输出:

['Example',
 'This is a sample sentence created to illustrate the problem.',
 'End of example']