如何在 Python 中从文件读取数字?

2025-02-20 09:23:00
admin
原创
30
摘要:问题描述:我想将文件中的数字读入二维数组。文件内容:包含的行w,hh`w`包含以空格分隔的整数的行例如:4 3 1 2 3 4 2 3 4 5 6 7 8 9 解决方案 1:假设您没有多余的空格:with open('file') as f: w, h = [int(x) for x in next(...

问题描述:

我想将文件中的数字读入二维数组。

文件内容:

  • 包含的行wh

  • h`w`包含以空格分隔的整数的行

例如:

4 3
1 2 3 4
2 3 4 5
6 7 8 9

解决方案 1:

假设您没有多余的空格:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

您可以将最后一个 for 循环压缩为嵌套列表推导:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

解决方案 2:

对我来说,这种看似简单的问题正是 Python 的用武之地。特别是如果你以前使用过 C++ 之类的语言,其中简单的文本解析可能很麻烦,那么你一定会非常感激 Python 可以为你提供的功能单元解决方案。我会使用几个内置函数和一些生成器表达式让它变得非常简单。

您将需要,,,,,open(name, mode)然后您可能需要使用几个生成器以 Python 方式将它们组合在一起。myfile.readlines()`mystring.split()`int(myval)

# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

在这里查找生成器表达式。它们可以真正将您的代码简化为离散的功能单元!想象一下在 C++ 中用 4 行代码做同样的事情……那将是一个怪物。尤其是列表生成器,当我还是 C++ 程序员时,我总是希望有这样的东西,而且我经常最终构建自定义函数来构造我想要的每种数组。

解决方案 3:

不确定为什么需要 w、h。如果这些值确实是必需的,并且意味着只应读取指定数量的行和列,那么您可以尝试以下操作:

output = []
with open(r'c:ile.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)

解决方案 4:

同时使用 python2(例如 Python 2.7.10)和 python3(例如 Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

另一种方法:同时使用 python2(例如 Python 2.7.10)和 python3(例如 Python 3.6.4),对于复杂矩阵请参见下面的示例(仅更改intcomplex

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

我更新了代码,此方法适用于初始文件中的任意数量的矩阵和任何类型的矩阵( int,, ) complexfloat`in.txt`

此程序产生矩阵乘法作为应用程序。正在使用 python2,为了使用 python3,请进行以下更改

print to print()

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

脚本:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

作为输入文件我采取 in.txt

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

输出如下:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

解决方案 5:

为了简化答案,这里有一个从文件读取整数并对其进行排序的程序

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

读取文件的每一行后将每个字符串转换为数字

nums.sort()

对数字进行排序

f.close()

f = open("input.txt", 'w')
for num in nums:
    f.write("%d
" %num)

f.close()

写回信就这么简单,希望这能有所帮助

解决方案 6:

我能想到的最短的方法是:

with open("file") as f:
    (w, h), data = [int(x) for x in f.readline().split()], [int(x) for x in f.read().split()]

如果看起来更整洁,您可以分离(w,h)和数据。

解决方案 7:

我在寻找 Pandas 解决方案时发现了这个问题。以下是将此文件读入数据框的两种方法。两种方法都使用pandas.read_csv

import pandas as pd

## Method 1:

# Ignore the header, read the rest of the file:
df = pd.read_csv('infile', header=None, sep=r's+', skiprows=1)

## Method 2:

# Read the header:
with open('infile') as infile:
    ncols, nrows = [int(x) for x in infile.readline().split()]

# Read the rest of the file, using the info from the header:
df = pd.read_csv('infile', header=None, sep=r's+', skiprows=1, nrows=nrows, usecols=range(ncols))

使用上述任一方法,您都可以获得以下数据框:

print(df)
   0  1  2  3
0  1  2  3  4
1  2  3  4  5
2  6  7  8  9

相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1325  
  IPD(Integrated Product Development)流程作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它涵盖了从产品概念产生到产品退市的整个生命周期,通过整合跨部门团队、优化流程等方式,显著提升产品开发的效率和质量,进而为项目的成功奠定坚实基础。深入探究IPD流程的五个阶段与项目成功之间...
IPD流程分为几个阶段   4  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,其中的创新管理与实践更是蕴含着丰富的经验和深刻的智慧,对众多企业具有重要的借鉴意义。IPD流程的核心架构IPD流程旨在打破部门墙,实现跨部门的高效协作,将产品开发视为一个整体的流程。它涵盖了从市场需求分析...
华为IPD是什么   3  
  IPD(Integrated Product Development)研发管理体系作为一种先进的产品开发模式,在众多企业的发展历程中发挥了至关重要的作用。它不仅仅是一套流程,更是一种理念,一种能够全方位提升企业竞争力,推动企业持续发展的有效工具。深入探究IPD研发管理体系如何助力企业持续发展,对于众多渴望在市场中立足并...
IPD管理流程   3  
  IPD(Integrated Product Development)流程管理旨在通过整合产品开发流程、团队和资源,实现产品的快速、高质量交付。在这一过程中,有效降低成本是企业提升竞争力的关键。通过优化IPD流程管理中的各个环节,可以在不牺牲产品质量和性能的前提下,实现成本的显著降低,为企业创造更大的价值。优化产品规划...
IPD流程分为几个阶段   4  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用