从字符串列表中提取每个单词

时间:2018-03-05 07:25:00

标签: python

我正在使用Python 我的清单是

str = ["Hello dude", "What is your name", "My name is Chetan"]

我想将字符串中每个句子中的每个单词分开并将其存储在new_list中。 new_list就像

new_list = ["Hello", "dude", "What", "is", "your", "name", "My", "name", 
            "is", "Chetan"]

我尝试了代码

for row in str:
    new_list.append(row.split(" "))

输出:

[['Hello', 'dude'], ['What', 'is', 'your', 'name'], ['My', 'name', 'is', 
  'Chetan']]

是列表

7 个答案:

答案 0 :(得分:3)

您可以使用itertools.chain

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

<强>样本

from itertools import chain

def split_list_of_words(list_):
    return list(chain.from_iterable(map(str.split, list_)))

答案 1 :(得分:1)

这应该有所帮助。而不是追加使用extend+=

str = ["Hello dude", "What is your name", "My name is Chetan"]
new_list = []
for row in str:
    new_list += row.split(" ") #or new_list.extend(row.split(" "))

print new_list

<强>输出

['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']

答案 2 :(得分:1)

你快到了。剩下要做的就是取消列表。

final_result = [x for sublist in new_list for x in sublist]

或者没有列表理解:

final_result = []
for sublist in new_list:
    for x in sublist:
        final_result.append(x)

当然,所有这一切都可以在一步完成,而不首先明确产生new_list。其他答案已经涵盖了这一点。

答案 3 :(得分:1)

你有,

value = ["Hello dude", "What is your name", "My name is Chetan"]

然后使用这个衬垫

' '.join(value).split()

答案 4 :(得分:1)

new_list = [x for y in str for x in y.split(" ")]

答案 5 :(得分:1)

试试这个: -

str = ["Hello dude", "What is your name", "My name is Chetan"]
ls = []
for i in str:
    x = i.split()
    ls +=x
print(ls)

答案 6 :(得分:0)

您可以尝试:

>>> new_list=[]
>>> str = ["Hello dude", "What is your name", "My name is Chetan"]
>>> for row in str:
      for data in row.split():
        new_list.append(data)

>>> new_list
['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']