繁体   English   中英

将带有几种不同类型数据的txt文件导入python。 如何使数据文件中的每一行成为类的实例?

[英]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  

此数据的非正式模式:

  • 大小(最多3位数字)
  • 品牌(最多10个字符)
  • 条件(最多10个字符)
  • 彩色(最多10位)
  • 零售价(最多6位数字)。

我将使用每行中特定数据的特定空间将其索引出来。 新数据集由~ 如何获取这些数据并为每组数据创建一个类的实例?

最好的做法是,建议每个文件具有一种数据类型

对于第一部分,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM