Python分割字符串数组

时间:2019-03-04 05:06:04

标签: python

我在Python中有一个看起来像这样的列表:

["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]

我想将每个字符串分成逗号分隔的列表并存储结果,并将每个单词都转换为小写:

[['hello','my','name','is','john'], ['good','afternoon','my','name','is','david'],['i','am','three','years','old']]

任何建议如何做到这一点? 谢谢。

6 个答案:

答案 0 :(得分:1)

您可以拆分每个字符串,然后过滤掉逗号以获取所需的列表列表。

a = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]
b = [[j.lower().replace(',', '') for j in i.split()] for i in a]

b
'''
Outputs:[['hello', 'my', 'name', 'is', 'john'],
         ['good', 'afternoon', 'my', 'name', 'is', 'david'],
         ['i', 'am', 'three', 'years', 'old']]
'''

答案 1 :(得分:1)

尝试以下代码:

x = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]

z = []

for i in x:
    # Replacing "," , converting to lower and then splitting
    z.append(i.replace(","," ").lower().split())

print z

输出:

[['hello', 'my', 'name', 'is', 'john'], ['good', 'afternoon', 'my', 'name', 'is', 'david'], ['i', 'am', 'three', 'years', 'old']]

答案 2 :(得分:1)

import re

def split_and_lower(s): 
    return list(map(str.lower, re.split(s, '[^\w]*'))) 

L = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"] 
result = list(map(split_and_lower, L))
print(result)

输出:

[['hello', 'my', 'name', 'is', 'john'],
 ['good', 'afternoon', 'my', 'name', 'is', 'david'],
 ['i', 'am', 'three', 'years', 'old']]

答案 3 :(得分:1)

我将进行替换和拆分。

strlist = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]
>>>[x.replace(',','').lower().split() for x in strlist]
[['hello', 'my', 'name', 'is', 'john'], ['good', 'afternoon', 'my', 'name', 'is', 'david'], ['i', 'am', 'three', 'years', 'old']]

答案 4 :(得分:1)

在每个单词上使用rstrip的方法:)

ls = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]

output_ls = [[word.lower().rstrip(',') for word in sentence.split()] for sentence in ls]

输出:

[['hello', 'my', 'name', 'is', 'john'], ['good', 'afternoon', 'my', 'name', 'is', 'david'], ['i', 'am', 'three', 'years', 'old']]

答案 5 :(得分:1)

您只需将逗号替换为空格,然后去除其余字符串。

strList = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]
[i.lower().replace(',', '').split() for i in strList]