将句子列表加入短语

时间:2018-05-01 22:49:20

标签: python list for-loop while-loop append

我有一个歌词抒情字符串列表,如下所示:

src: url('./flags/en.svg');

即。每个歌词以换行符结尾,有些以句点结尾,换行符为新行。

我想做的是制作一个如下所示的列表:

[' Extending a life\n', 'With total resistance\n', 
'To fatal disease\n', 'Future methods of science.\n', 
'Replacing what is real\n', 'By using technology\n', 
'Population control\n', 'Selecting those who will breed.\n',
'A specific type of form\n', 'Chosen for the unborn.\n', 
'A mind without emotion\n', 'Progressive anatomy.\n']

即。新列表的每个值都是一个完整的歌词字符串,每个完整的歌词结尾都有句号。

我知道如何只对一部分歌词进行此操作:

[' Extending a life\n With total resistance\n To fatal disease\n Future methods of science.\n', 
'Replacing what is real\n By using technology\n Population control\n Selecting those who will breed.\n',
'A specific type of form\n Chosen for the unborn.\n', 
'A mind without emotion\n Progressive anatomy.\n'] 

此代码适用于需要以上述格式加入的歌词的各个部分。

我很难概括这个功能来处理整个原始歌词列表。任何建议将不胜感激。

**请注意,传入该功能的歌词是正确排序的,即根据歌曲排序。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,只需

即可完成
[s + '.\n' for s in ' '.join(lyrics).split('.\n')[:-1]]

答案 1 :(得分:0)

您可以将itertools.groupbyre

一起使用
import re
import itertools
d = [' Extending a life\n', 'With total resistance\n', 'To fatal disease\n', 'Future methods of science.\n', 'Replacing what is real\n', 'By using technology\n', 'Population control\n', 'Selecting those who will breed.\n', 'A specific type of form\n', 'Chosen for the unborn.\n', 'A mind without emotion\n', 'Progressive anatomy.\n']
results = [list(b) for _, b in itertools.groupby(d, key=lambda x:bool(re.findall('\.\n', x)))]
final_result = [' '.join(results[i]+results[i+1]) for i in range(0, len(results), 2)]

输出:

[' Extending a life\n With total resistance\n To fatal disease\n Future methods of science.\n', 'Replacing what is real\n By using technology\n Population control\n Selecting those who will breed.\n', 'A specific type of form\n Chosen for the unborn.\n', 'A mind without emotion\n Progressive anatomy.\n']

答案 2 :(得分:0)

这是使用for循环的一种方式。

lst = [' Extending a life\n', 'With total resistance\n', 
       'To fatal disease\n', 'Future methods of science.\n', 
       'Replacing what is real\n', 'By using technology\n', 
       'Population control\n', 'Selecting those who will breed.\n',
       'A specific type of form\n', 'Chosen for the unborn.\n', 
       'A mind without emotion\n', 'Progressive anatomy.\n']

def formatter(x):
    res = []
    part = []
    for i in x:
        part.append(i)
        if i[-2] == '.':
            res.append(part[:])
            part.clear()
    return [''.join(j) for j in res]

res = formatter(lst)

[' Extending a life\nWith total resistance\nTo fatal disease\nFuture methods of science.\n',
 'Replacing what is real\nBy using technology\nPopulation control\nSelecting those who will breed.\n',
 'A specific type of form\nChosen for the unborn.\n',
 'A mind without emotion\nProgressive anatomy.\n']