从阅读中删除空格

时间:2019-02-05 12:37:04

标签: python

我正试图从dat文件中读取信息,但我正在发疯,看起来像“”的字符仍在其中,我似乎无法删除它们,我目前正在尝试的操作类似于这个:

import numpy as np


def read_in():
    cities = []
    file = open('cities.dat', "r")
    for line in file:
        for city in line.split():
            city = city.replace("'", "")
            cities.append(city)
    file.close()
    cities = np.array(cities)
    return cities

有人可以帮我吗,您如何删除这些标志,更换似乎无法解决。

1 个答案:

答案 0 :(得分:0)

看起来您的原始数据是0.4000, 0.4439;。您已经在,0之间的空白处分割了数据,这使标点符号留在了字符串中,例如['0.4000,' '0.4439;']。如果您期望数字,那么

for line in file:
    city = [float(c.strip(";")) for c in line.split(",")]  
    # split on the comma
    # then strip semicolons
    # then convert to float
    cities.append(city)