我想在字符串列表中按單詞拆分字符串。我嘗試迭代列表,但是我收到一個錯誤,即 split 不是列表方法。需要的結果是:[["Hi", ",", "how", "are", "you", "?"], ["look", ":", "over", ",", "there"]代碼:list1=["Hi, how are you?", "look: over, there"]list2=[]for x in list1: list2=list1.split()print(list2)
1 回答

湖上湖
TA貢獻2003條經驗 獲得超2個贊
使用正則表達式 --> re.split。
前任:
import re
list1 = ["Hi, how are you?", "look: over, there"]
result = [[j for j in re.split(r"([^A-Za-z])", i) if j.strip()] for i in list1 ]
print(result)
輸出:
[['Hi', ',', 'how', 'are', 'you', '?'], ['look', ':', 'over', ',', 'there']]
添加回答
舉報
0/150
提交
取消