【问题标题】:Loop through elements in list of strings and combine if condition is met [duplicate]遍历字符串列表中的元素并在满足条件时组合[重复]
【发布时间】:2020-03-24 21:18:52
【问题描述】:

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

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',所以我试图将它们结合起来以实现更合理的段落列表。另一方面,如果有人对如何将原始提取的文本拆分成段落有更好的想法,那也很棒。提前感谢您的帮助!

【问题讨论】:

  • 我已经标记了几个副本中的一个,它需要解决这个问题——我想你已经掌握了其他的。制作新清单;用大写字母为每个字符串开始一个新元素,在你去的时候附加小写字母。如果需要,请使用嵌套循环解决该问题,但请在尝试级联和连接的单线之前解决它。

标签: python list


【解决方案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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2016-03-24
    • 2019-10-16
    • 2017-04-07
    • 2020-03-07
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多