如何将带换行的歌词字符串列表合并为短语?
嘿,我来帮你搞定这个歌词列表转短语的问题!你的输入列表里每个条目都带换行符,部分还加了末尾的句号,核心就是先清理这些冗余字符,再按需合并成短语。
实现思路
- 清理单个歌词条目:先移除首尾的空白(包括换行符、多余空格),再去掉末尾的句号(避免影响短语格式)
- 合并短语:可以选择保留短语列表,或者把所有短语拼接成一个连贯的字符串
Python 代码实现
首先定义你的原始歌词列表:
lyrics = [' 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 clean_lyric(line): # 移除首尾所有空白(换行、空格等) cleaned = line.strip() # 移除末尾的句号(仅针对末尾的,不影响中间内容) cleaned = cleaned.rstrip('.') return cleaned # 得到清理后的短语列表 cleaned_phrases = [clean_lyric(line) for line in lyrics] # 可选:合并成单个连贯的短语字符串 merged_full_phrase = ' '.join(cleaned_phrases)
效果说明
cleaned_phrases会输出干净的短语列表:['Extending a life', 'With total resistance', 'To fatal disease', 'Future methods of science', 'Replacing what is real', 'By using technology', 'Population control', 'Selecting those who will breed', 'A specific type of form', 'Chosen for the unborn', 'A mind without emotion', 'Progressive anatomy']merged_full_phrase会输出所有短语拼接后的长字符串:"Extending a life With total resistance To fatal disease Future methods of science Replacing what is real By using technology Population control Selecting those who will breed A specific type of form Chosen for the unborn A mind without emotion Progressive anatomy"
如果需要用其他分隔符(比如逗号、换行),只需要修改join的参数即可,比如', '.join(cleaned_phrases)会用逗号分隔每个短语。
内容的提问来源于stack exchange,提问作者Andrew Louis
相关产品推荐
相关产品推荐

