![](/img/trans.png)
[英]How do I import data with different types from file into a Python Numpy array?
[英]Import an txt file into python with several different types of data. How do I make every line in the data file into an instance of my class?
我最近开始使用python进行编码,现在正尝试获取一个文本文件,其中包含有关特定类型服装的尺寸,价格和品牌的数据值。 我已经设法使用以下命令将文本文件及其所有信息导入:
def buyshop():
print("You have selected to buy clothing. What would you like to buy?")
print("\n Articles available: \n")
handle = open("Clothing Shop On Sale.txt", "r")
reading = handle.read()
reading =(re.sub("'|(|)", "", reading))
我想获取文件中的数据,通常看起来像这样的原始数据:
~24 adidas bad blue 2695
~12 adidas excellent white 2200
此数据的非正式模式:
我将使用每行中特定数据的特定空间将其索引出来。 新数据集由~
。 如何获取这些数据并为每组数据创建一个类的实例?
最好的做法是,建议每个文件具有一种数据类型
对于第一部分,您可以使用csv
模块来帮助您。
import csv
with open("shop_file", "r") as fd:
a = csv.reader(fd, delimiter=' ')
result = [line for line in a if line] #remove empty line
结果= [['~24', 'adidas', 'bad', 'blue', '2695'], ['~12', 'adidas', 'excellent', 'white', '2200']]
对于第二部分,您可以使用regex或json来更轻松地管理数据。
如果您使用readline()函数读取文件,请使用以下代码获取变量的值
line='~24 adidas bad blue 2695'.lstrip('~') #removes the leading '~'
size,brand,condition,color,price=line.split() #use line.split('\t') if you use tab to seperate the values
确保将其放在try-except块中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.