【问题标题】:load the data with numpy.loadtxt and replace a new line in a file with command用 numpy.loadtxt 加载数据并用命令替换文件中的新行
【发布时间】:2018-07-16 08:48:52
【问题描述】:

这是我的第一个问题。

我尝试使用 Python 加载数据文件。 文件demo.txt 类似如下。

12,23,34.5,56,

78,29,33,

44,55,66,78,59,100

(文件的行数不同,每行的列数可能不同。我需要处理很多数据文件)

numpy.loadtxt("demo.txt",delimiter=",") 

给出错误消息“could not convert string to float:”。

为了解决这个问题,我尝试使用命令

sed -i -e 's/,\n/,/g' demo.txt

删除每行末尾的换行符以将所有行合并为一行。但是失败了。

但是,在VIM中,可以使用":s/,\n/,/g"来删除换行符。

因此,我的问题是

  1. 是否可以在不修改文件的情况下在python中加载数据文件?

  2. 1234563每行末尾的换行符将所有行合并为一行?没有所有行的换行符,我可以很容易地用 numpy.loadtxt 读取数据。

最好的问候,

一屏

【问题讨论】:

标签: python numpy vim sed


【解决方案1】:

从带有tr -d '\n' 的文件中删除所有换行符:

$ echo -e "some\nfile\nwith\n\newlines" > file_with_newlines
$ cat file_with_newlines 
some
file
with

ewlines
$ cat file_with_newlines | tr -d '\n' > file_without_newlines
$ cat file_without_newlines 
somefilewithewlines$ 

我不知道这是否真的可以帮助您解决 numpy 问题,但它会从文件中删除所有 (UNIX) 换行符。

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2013-09-25
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多