簡體   English   中英

Python Splitting數組字符串

[英]Python Splitting Array of Strings

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

有任何建議如何做到這一點? 謝謝。

您可以拆分每個字符串,然后過濾掉逗號以獲取所需的列表列表。

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

試試以下代碼:

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

我會選擇替換和拆分。

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

在每個單詞上使用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']]

您可以簡單地用空格替換逗號並刪除字符串的其余部分。

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM