如何在python中将标记和字符列表(包括标点符号和符号)组合成一个单独的字符串



我正在尝试加入一个单词和字符列表,例如下面的列表(ls(,并将其转换为一个单独的、格式正确的字符串(句子(,用于列表集合。

ls = ['"', 'Time', '"', 'magazine', 'said' 'the', 'film', 'was',
'"', 'a', 'multimillion', 'dollar', 'improvisation', 'that',
'does', 'everything', 'but', 'what', 'the', 'title', 'promises',
'"', 'and', 'suggested', 'that', '"', 'writer', 'George',
'Axelrod', '(', '"', 'The', 'Seven', 'Year', 'Itch', '"', ')',
'and', 'director', 'Richard', 'Quine', 'should', 'have', 'taken',
'a', 'hint', 'from', 'Holden', "'s", 'character', 'Richard',
'Benson', 'who', 'writes', 'his', 'movie', ',', 'takes', 'a',
'long', 'sober', 'look', 'at', 'what', 'he', 'has', 'wrought',
',', 'and', 'burns', 'it', '.', '"']
sentence = '"Time" magazine said the film was "a multimillion dollar improvisation that does everything but what the title promises" and suggested that "writer George Axelrod ("The Seven Year Itch") and director Richard Quine should have taken a hint from Holden's character Richard Benson who writes his movie, takes a long sober look at what he has wrought, and burns it."'

我尝试过一种基于规则的方法,根据下一个元素的内容在元素后面添加一个空格,但我的方法最终是一段非常长的代码,其中包含了我能想到的任意多种情况的规则,比如括号或引号。有没有一种方法可以更有效地将这个列表连接到一个格式正确的句子中?

我认为一个简单的for应该可以做到这一点:

sentence = ""
for word in ls:
if (word == ',' or word == '.') and sentence != '': 
sentence = sentence[:-1] #removing the last space added
sentence += word 
if word != '"' or word != '(':
sentence += ' ' #adding a space after each word

最新更新