Python如何删除数字之间的空格

时间:2018-02-08 05:01:04

标签: python numbers whitespace tabular

我有一个包含4列数字的表,但是在某些列中有空格。

当我尝试读取表格时,会产生错误:

  

ValueError:无法将字符串转换为float。

我解决了这个错误,手动删除空白,它可以工作,但我想知道Python是否有一些解决方案,以删除数字之间的空格

我删除空格的代码:

path = 'C:\Users\laboratorio\Desktop\waveletspy\prueba.txt'
path1 = 'C:\Users\laboratorio\Desktop\waveletspy\prueba1.txt'

clean_lines = []
with open(path, "r") as f:
    lines = (line.strip() for line in f.readlines() if len(line.strip()))     
    clean_lines = [l.strip() for l in lines if l.strip()]
    with open(path2, "w") as f:
      f.writelines('\n'.join(clean_lines))

原始表:

 Y 2457620.83012      -0.433      0.004  
 Y 2457620.83100      -0.439       0.005  
 Y 2457620.83518      -0.459      0.004   
Y 2457620.83600      -0.470      0.005   
Y 2457620.83684      -0.498      0.004   
Y 2457620.83767      -0.480      0.005   
Y 2457620.83851      -0.490      0.005   

W 2457620.83934 -0.516 0.004

我想要这样的东西

Y 2457620.83012 -0.433 0.004
Y 2457620.83100 -0.439 0.005
Y 2457620.83518 -0.459 0.004
Y 2457620.83600 -0.470 0.005
Y 2457620.83684 -0.498 0.004
Y 2457620.83767 -0.480 0.005
Y 2457620.83851 -0.490 0.005
Y 2457620.83934 -0.516 0.004

3 个答案:

答案 0 :(得分:0)

让每行中的每个单词分别用一个空格分隔:

代码:

clean_lines = [' '.join([w.strip() for w in l.strip().split()])
               for l in lines if l.strip()]

测试代码:

with open('file1', "r") as f:
    lines = (line.strip() for line in f.readlines() if len(line.strip()))
    clean_lines = [' '.join([w.strip() for w in l.strip().split()])
                   for l in lines if l.strip()]
    for line in clean_lines:
        print(line)

结果:

Y 2457620.83012 -0.433 0.004
Y 2457620.83100 -0.439 0.005
Y 2457620.83518 -0.459 0.004
Y 2457620.83600 -0.470 0.005
Y 2457620.83684 -0.498 0.004
Y 2457620.83767 -0.480 0.005
Y 2457620.83851 -0.490 0.005

答案 1 :(得分:0)

您可以使用正则表达式执行此操作。首先用一个空格替换所有出现的多个空白字符,然后从每行的开头和结尾修剪空格:

CONCAT(LEFT(DAYNAME(STR_TO_DATE(CONCAT(YEAR(`order_date`),LPAD(WEEKOFYEAR(`order_date`),2,'0'),' ','Monday'), '%X%V %W')),3),' ',
            EXTRACT(DAY FROM (`order_date` - INTERVAL WEEKDAY(`order_date`) Day)),' ',
    LEFT(MONTHNAME(STR_TO_DATE(CONCAT(YEAR(`order_date`),LPAD(WEEKOFYEAR(`order_date`),2,'0'),' ','Monday'), '%X%V %W')),3)) AS mondayText

答案 2 :(得分:0)

您可以使用正则表达式来完成此操作。它将删除所有不寻常的空格。

代码:

"filled"

<强>结果:

import re
path = 'C:\Users\laboratorio\Desktop\waveletspy\prueba.txt'
path1 = 'C:\Users\laboratorio\Desktop\waveletspy\prueba1.txt'

clean_lines = []
with open(path, "r") as f:
    lines = (line.strip() for line in f.readlines() if len(line.strip()))     
    clean_lines = [l.strip() for l in lines if l.strip()]
    with open(path2, "w") as f:
        for i in clean_lines:
            f.writelines(re.sub(r'\s+', ' ', str(i)))
            f.writelines('\n')