Python拆分字符串数组

4

我有一个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']]

有什么建议可以实现这个吗? 谢谢。

1
[[j.lower() for j in i.replace(",","").split()] for i in mylist] - itzMEonTV
@itzMEonTV 你忘了去掉逗号。 - kerwei
6个回答

3
你可以简单地用空格替换逗号,并去掉字符串的其余部分。
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]

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
就快了……hello保留了逗号,我认为你想要的不是j!= ',',因为这里的j是每个单词 :) - LeKhan9

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']]

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']]

1

我会选择使用replace和split。

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']]

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']]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接