【问题标题】:Python: read various data-type from filePython:从文件中读取各种数据类型
【发布时间】:2015-04-12 14:31:07
【问题描述】:

我正在从 matlab 切换到 python。 我要导入的数据是这样的

4
6
2
1
2.0E8
0.2
0.002

1 2 6
2 3 4
2 4 5
2 5 6

0 0
1 0
2 0
2 1
1 1
0 1

4 0 -150

1 1 1
6 1 1

这就是我在matlab中读到的方式

FP1=fopen('471220580.txt','rt');
NELEM=fscanf(FP1,'%d',1);
NPION=fscanf(FP1,'%d',1);
NVFIX=fscanf(FP1,'%d',1);
NFORCE=fscanf(FP1,'%d',1);
YOUNG=fscanf(FP1,'%e',1);
POISS=fscanf(FP1,'%f',1);
THICK =fscanf(FP1,'%f',1);
LNODS=fscanf(FP1,'%d',[3, NELEM])';  
COORD=fscanf(FP1,'%f',[2,NPION])';  
FORCE=fscanf(FP1,'%f',[3,NFORCE])';  
FIXED=fscanf(FP1,'%d',[3,NVFIX])';  

如何在python 中导入这些数据?我在python 中没有找到fscanf 的等价物。

对于What is the equivalent of Matlab 'fscanf' in Python? numpy.loadtxt 需要 Each row in the text file must have the same number of values。这不适合我的情况。

【问题讨论】:

  • 你还没有回答你的最后一个问题...可能想放慢一些问题?
  • @DonkeyKong,我已经检查了答案,numpy.loadtxt 需要 Each row in the text file must have the same number of values.
  • @DonkeyKong,关于我之前的问题,似乎人们认为直接在脚本中创建矩阵不好,所以我创建了这个帖子。上一个被删除了。

标签: python matlab numpy scipy


【解决方案1】:

像这样循环遍历文件中的行

for line in open("file.txt"):
     parse(line)

parse 方法是将行作为输入并输出整数、浮点数或整数列表的方法。

对于整数 -> var = int(line)

对于浮动 -> var = float(line)

对于整数列表 -> var = map(int, line.split())

对于矩阵 -> 考虑您阅读想要一个 m X n 矩阵。 所以读入m 行,从上面的循环中读取 -

matrix = []

count = m
for line in open():
    if count > 0:
        matrix.append(map(int, line.split()))

【讨论】:

  • 但是我怎样才能把它读成一个矩阵呢? LNODS=fscanf(FP1,'%d',[3, NELEM]); 这将生成一个矩阵。
【解决方案2】:
with open('471220580.txt') as text_file:
    all_numbers = text_file.read().split("\n")
    all_numbers = filter(None, all_numbers)
    #the all_numbers list contains all the distinct values from the file
    #Now to initialize various variables you can use following methods:

    #Method1:
    NELEM = all_numbers[0]
    NPION = all_numbers[1]
    #and so on ... 

    #Note: Keep in mind that the values stored in these variables is of type str


   #Method2:
   NELEM, NIPON ,... = all_numbers

使用Method1 优于Method2 的优点是您可以在method1 中使用类型转换,而您可以通过使用var1 = type(var) 来实现这一点

NELEM = int(all_numbers[0])
NPION = int(all_numbers[1])
POISS = float(all_numbers[5])

对于构成矩阵的第 9-12 行,我们可以将矩阵表示为列表的列表。

matrix_row1 = map(int, all_numbers[9])    #[1, 2, 3]
matrix_row2 = map(int, all_numbers[10])   #[4, 5, 6]
matrix_row3 = map(int, all_numbers[11])   #[7, 8, 9]

matrix = [matrix_row1, matrix_row2, matrix_row3]
#[[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]

【讨论】:

  • 但是我怎样才能找到matrix?我需要手动计算数字吗?
  • 你在说哪个matrix
  • 例如,来自line 9-12 是一个矩阵。但是好像我们把所有的数字都变成了一个数组?如何方便地将其导入matrix
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
相关资源
最近更新 更多