我有一個文件與我讀的一些數據,分裂與space
,,
,\n
並將其放入一個矩陣。 但我的代碼返回一個多餘的空白字符到我的矩陣。任何人都可以幫我找到這個bug嗎?謝謝。 代碼:python分裂返回一個多餘的空白字符
import re
lines = [re.split('[,\n ]',line) for line in open('lines.txt')]
print lines
輸入:
395,0 398,100
398,100 488,196
488,196 544,233
544,233 506,301
506,301 425,344
425,344 336,355
336,355 271,319
271,319 293,264
293,264 328,232
328,232 329,170
329,170 267,175
267,175 228,199
228,199 214,220
214,220 80,268
80,268 0,273
0,183 96,176
96,176 168,92
168,92 252,124
252,124 300,88
300,88 303,40
303,40 309,0
輸出(第5欄是過量):
[['395', '0', '398', '100', ''], ['398', '100', '488', '196', ''], ['488', '196', '544', '233', ''], ['544', '233', '506', '301', ''], ['506', '301', '425', '344', ''], ['425', '344', '336', '355', ''], ['336', '355', '271', '319', ''], ['271', '319', '293', '264', ''], ['293', '264', '328', '232', ''], ['328', '232', '329', '170', ''], ['329', '170', '267', '175', ''], ['267', '175', '228', '199', ''], ['228', '199', '214', '220', ''], ['214', '220', '80', '268', ''], ['80', '268', '0', '273', ''], ['0', '183', '96', '176', ''], ['96', '176', '168', '92', ''], ['168', '92', '252', '124', ''], ['252', '124', '300', '88', ''], ['300', '88', '303', '40', ''], ['303', '40', '309', '0', '']]
你不這個任務不需要regex,你可以簡單地使用'csv'模塊解析你的文件,它將返回一個可迭代對象包含分割項的元組。 – Kasramvd
'[re.split(r'[,\ s] +',line.strip())for line in open('lines.txt')]' – anubhava