简体   繁体   English

如何将短语列表转换为单词列表?

[英]How to convert a list of phrases into list of words?

I want to convert a list which contains both phrases and words to a list which contains only words.我想将包含短语和单词的列表转换为仅包含单词的列表。 For example, if the input is:例如,如果输入是:

list_of_phrases_and_words = ['I am', 'John', 'michael and', 'I am', '16', 
    'years', 'old']

The expected output is:预期的输出是:

list_of_words = ['I', 'am', 'John', 'michael', 'and', 'I', 'am', '16', 'years', 'old']

What is the efficient way to achieve this is in Python?在 Python 中实现这一目标的有效方法是什么?

You can use a list comprehension:您可以使用列表理解:

list_of_words = [
    word
    for phrase in list_of_phrases_and_words
    for word in phrase.split()
]

An alternative that might be slightly less efficient for larger lists would be to first create a large string containing everything and then splitting it:对于较大的列表,可能效率稍低的替代方法是首先创建一个包含所有内容的大字符串,然后将其拆分:

list_of_words = " ".join(list_of_phrases_and_words).split()

诀窍是一个嵌套的 for 循环,您可以在空格字符“”上进行拆分。

words = [word for phrase in list_of_phrases_and_words for word in phrase.split(" ")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表中的所有单词和短语放入搜索表达式(Python) - How to put all words and phrases in list into a search expression (Python) 如何将具有词组的str列表转换为int列表? - How do I convert a str list that has phrases to a int list? 如何从 python 中的数字和单词的原始列表中创建仅包含数字和单词/短语的新列表? - How to create a new list with just numbers and words/phrases from a original list with both numbers and words in python? 从列表中删除带有自定义停用词的短语 - Removing phrases with custom stop words from a list 给定单词列表,用它们组成短语的子集 - Given a list of words, make a subset of phrases with them 检查包含单词和短语的列表元素是否存在于另一个列表中 - Check if elements of list with words and phrases exist in another list 如何将词组列表拆分为单词,以便可以对它们使用计数器? - How do I split a list of phrases into words so I can use counter on them? 从不在基本字符串中的字符串列表中提取单个单词或短语 - Extract single words or phrases from list of strings which are not in base string 根据列表中的多个单词从 pandas dataframe 中提取所有短语 - Extract all phrases from a pandas dataframe based on multiple words in list 如何在Python 2中搜索列表内的多个短语 - How to search for multiple phrases inside a list in Python 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM