【问题标题】:Taking array from txt file and setting as constructor arguments in python从 txt 文件中获取数组并在 python 中设置为构造函数参数
【发布时间】:2020-04-21 07:10:22
【问题描述】:

所以我目前正在使用类作为课程项目的一部分,并希望使用从文本文件中获取的数组作为参数。以下是我尝试过的,有人可以提出任何帮助吗?

class Trips:
    destination = ""
    dep_date = ""
    airline = ""
    ret_date = ""

    def __init__(self, destination, dep_date, airline, ret_date):
        self.destination = destination
        self.dep_date = dep_date
        self.airline = airline
        self.ret_date = ret_date

def get_trips():
    tripsdb = open("tripsdb.txt")
    content = tripsdb.read()
    tripsdb.close()
    trips = content.split("\n")
    trips.pop(len(trips)-1)
    return trips

trips = get_trips()
print(trips)
#this prints ['Lisbon, 28.02.2020, TAP, 03.03.2020', 'Fortaleza, 20.06.2020, TAP, 25.06.2020'] all trips in text file
print(trips[0])
#this prints Lisbon, 28.02.2020, TAP, 03.03.2020 the content of the first array

trip1 = Trips(trips[0])
print(trip1)
#this prints Traceback (most recent call last):
  File "class.py", line 25, in <module>
    trip1 = Trips(trips[0])
TypeError: __init__() missing 3 required positional arguments: 'dep_date', 'airline', and 'ret_date'

trip1 = Trips(*trips[0])
print(trip1)
Traceback (most recent call last):
  File "class.py", line 25, in <module>
    trip1 = Trips(*trips[0])
TypeError: __init__() takes 5 positional arguments but 36 were given

最终我想要它做的是让数组成为 Trips 的参数。

【问题讨论】:

  • trips 是一个列表,而不是一个数组 - 在 Python 中。

标签: python arrays object constructor arguments


【解决方案1】:

trips[0] 只是一个字符串,这就是*trips[0] 产生 36 个参数(每个字符)的原因。您需要先在, 上拆分您的字符串。

Trips(*trips[0].split(',')) 应该可以正常工作。

为了消除split(',') 之后的空格,您可以这样做:

trip_data = [v.strip() for v in trips[0].split(',')]
trip1 = Trips(*trip_data)

【讨论】:

  • 或使用csv 模块读取文件,然后将行提供给类。
  • 谢谢大家,我没有注意到它已经变成了一个字符串。拆分建议非常有效@olisch。我也去看看 csv 模块!
猜你喜欢
  • 2016-03-11
  • 1970-01-01
  • 2022-01-15
  • 2014-04-10
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
相关资源
最近更新 更多