首页 > 解决方案 > 如何将列表的行合并成短语(帮助完成代码)?

问题描述

我有一个清单如下:

[
 '"The investment would also benefit the company’s',
 'ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material',
 'usage by replacing cardboard boxes with reusable',
 'plastic tote bins and cutting daily vehicle movements through the accurate management of',
 'fixed cyling schedules.",',
 '"The core brands of Cadbury Roses and Heroes are',
 'produced and packaged at the Bournville production facility. The wrapped chocolates that make',
 'up these assortments have traditionally been',
 'managed through the factory in cardboard boxes.'
]

我需要"将行删除并合并到短语中才能获得以下结果:

[
 'The investment would also benefit the company’s ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material usage by replacing cardboard boxes with reusable plastic tote bins and cutting daily vehicle movements through the accurate management of fixed cyling schedules.',
 'The core brands of Cadbury Roses and Heroes are produced and packaged at the Bournville production facility.",
 'The wrapped chocolates that make up these assortments have traditionally been managed through the factory in cardboard boxes.'
]

我该怎么做?

这就是我开始做的事情:

final_list = []
temp_list = []
for l in lines:
    temp_list.append(l) 
    if "." in l:
        phrase = ' '.join(map(str, temp_list)) 
        final_list.append(phrase)
        temp_list = []

final_list

它生成以下输出,这与我的预期输出不完全匹配:

[
 '"The investment would also benefit the company’s ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material usage by replacing cardboard boxes with reusable plastic tote bins and cutting daily vehicle movements through the accurate management of fixed cyling schedules.",',
 '"The core brands of Cadbury Roses and Heroes are produced and packaged at the Bournville production facility. The wrapped chocolates that make',
 'up these assortments have traditionally been managed through the factory in cardboard boxes.'
 ]
  

标签: pythonstringlist

解决方案


试试下面的。它只会检查结尾是否有句点,它会删除您在测试和输出案例之间删除的额外引号和逗号,但不会删除额外字符。

final_list = []
temp_list = []
for l in lines:
    temp_list.append(l) 
    if "." in l[-3:]:
        phrase = ' '.join(map(str, temp_list)).strip('", ')
        final_list.append(phrase)
        temp_list = []

print(final_list)

推荐阅读