【问题标题】:how do I read the input file as integers in Python [duplicate]如何在 Python 中将输入文件读取为整数 [重复]
【发布时间】:2015-05-18 02:31:07
【问题描述】:

当多项式的系数被用作输入时,我应该制作一个给出有理根的程序。

如何将输入文件读取为整数? 这是我用于读取文件的代码:

def input_file(filename):
    with open(filename, "rt") as file:
        read_data = file.read()
    return read_data 

【问题讨论】:

  • 文件的格式是什么?
  • @TimBiegeleisen 输入文件是一个txt文件
  • 好的...但是数字是如何存储的?逐列 CSV,作为单行等?
  • @TimBiegeleisen 哦,它在 4 行中
  • @connie “哦,它在 4 行中” 那是无响应的。

标签: python


【解决方案1】:

如果您愿意使用 numpy 数组,则可以使用 loadtxt() 函数。还有一个选项可以跳过标题行。您还可以设置一个选项以导入为整数值。 'dtype' 如果我没记错的话。如果你需要一个列表或其他类型的输出,你应该能够适当地进行类型转换。

import numpy as np
def input_file(filename):
    with open(filename, "rt") as file:
        arr = np.loadtxt(file)
    return arr 

r = input_file('test.txt')

更多信息请访问 http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

【讨论】:

    【解决方案2】:

    这个问题已经详细讨论过:

    How to read numbers from file in Python?

    例如,基本思想是读取每一行并根据需要对其进行解析

    你的例子可能是:

    def input_file(filename):
        coefficients = []
        with open(filename,'rt') as file:
            for line in file: # loop over each line
                coefficients.append(float(line)) # parse them in some way
        return coefficients
    

    如果我们的系数比 1-number-1-line 更复杂,你的解析方法就得改变;我怀疑你的情况需要什么太复杂的东西

    ...
    for line in file:
        # say the numbers are separated by an underscore on each line
        coefficients.append([float(coef) for coef in line.split('_')])
    

    您以什么格式检索它们并不重要。重要的是您将它们转换为某种数字,因为输入通常是读取 aa字符串

    【讨论】:

    • 如果我的输入文件中的数字有逗号怎么办?比如 0,-2,1,15?
    • 看看第二个代码示例。读入一行,使用 split 方法将其拆分为您想要的任何轮廓符(在我的示例中,我使用下划线,您需要逗号),然后将其转换为一个数字并将其添加到列表中。该方法返回一个数字列表,这将是您的系数;你可以返回任何你想要的格式
    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2017-10-07
    • 2015-07-11
    相关资源
    最近更新 更多