繁体   English   中英

错误读取 python 中文本文件的行

[英]Incorrectly reading lines of a text File in python

所以基本上我想迭代具有这种格式的文本文件的行:

-----------------------------------------
Code: 0123456789
EGGS: 3 7.00 21.00
BACON: 1 3.50 3.50
COFFEE: 2 14.20 28.40
TOTAL: 52.90
----------------------------------------- 

我有以下代码来逐行阅读:

with open(filename, "rt", encoding="utf-8") as f:
   for line in f:
       prevline = line
       line.split()

       if '-' in line:
           temp = f.readline().split(':') #Get Code
           print(temp)
           AFM = temp[1]
           print(AFM)
       else:
           tempProducts = line.split(':') #Get Product in a list 
           productName = tempProducts[0] #Store Product Name in a variable
           productStats = tempProducts[1] #Store Product Stats in a list
           productStats = productStats.split(" ")
           for value in productStats:
               valueArray.append(float(value))
               products.update({productName:valueArray})
       if '-' in f.readline():
           rec = Receipt(AFM,products)
           products={}
           valueArray=[]
           receipts.append(rec)
       else:
           line=prevline

请注意,我想跳过带有'------------'字符的行代码可以工作,但它会继续读取第二行,然后是第四行,然后是第六行(代码,培根,总计)。 问题是我该如何解决这个问题。编辑:文件中有多个收据,所以我每次都需要跳过带有'----------'的行。

with open(filename, "rt", encoding="utf-8") as f:
    old_list = [] # Saving all the lines including '----' 
       for line in f:
           old_list.append(line)
    new_list = old_list[1:-1] # new list which removes the '----' lines

您可以使用 your.split 逻辑遍历 new_list 。

看看这是否有效

with open(filename, "rt", encoding="utf-8") as f:
    valueArray = []
    for line in f:
        if not '-' in line:
            if 'Code' in line:
                AFM = line.split(':')[1]
                print(AFM)
                valueArray = []
                products = {}
            else:
                tempProducts = line.split(':')  # Get Product in a list
                productName = tempProducts[0]  # Store Product Name in a variable
                productStats = tempProducts[1]  # Store Product Stats in a list
                productStats_list = productStats.split(" ")
                for value in productStats:
                    valueArray.append(float(value))
                products.update({productName: valueArray})
                if 'TOTAL' in line:
                    rec = Receipt(AFM, products)
                    receipts.append(rec)

对于现在看到这篇文章的任何人都认为它已关闭,我没有提供足够的信息并且代码被搞砸了。 抱歉浪费您的时间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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