如何从文本文件中读取python中的下一行

发布于 2025-02-04 14:41:34 字数 1302 浏览 2 评论 0原文

我有一个类似于此类的文本文件,该文件是从服务器读取的:

Jo's Deli Express
Potatoes
30
Fish
20
Chicken Meat
15

Margo's Grocery
Beans
20
Carrots
15
Apples
30

两家商店被一个空行分开,以便我们可以计算每个商店的值。

我想计算这些商店的产品的总收入(单个商品的产品 *价值的数字)以及总共购买的商品数量。

我遇到的问题是我不知道如何将项目名称链接到下面的值。因此,python需要知道,当它正在阅读每一行时,应该知道将什么值乘以下面的数字。例如,一块马铃薯的成本为0.70,因此它应该将0.7乘以30,依此类推,依此类推。

这是我到目前为止编码的内容:

user = input("Enter file name - AprilSales, MaySales, or JuneSales")
revenue = 0
response = None

try:
    response = urllib.request.urlopen("link of server" + user + ".txt")
except:
    print("File not found")

fileData = response.read().splitlines()

for i in range(len(fileData)):
    fileData[i] = fileData[i].decode('utf-8')

for line in fileData:
     if len(line) != 0:
         #try block to only convert the strings which are able to be converted to ints and leave the rest
         try: 
              print(int(line))
         except:
              print(line)
              if(line == "Potatoes"):
                  revenue = revenue + int(line.next() * 0.7)
              if(line == "Fish"):
                  revenue = revenue + int(line.next() * 1.50)
              if(line == "Chicken"):
                  revenue = revenue + int(line.next() * 1.70)
      else:
        break

I have a text file that resembles like this which is read from a server:

Jo's Deli Express
Potatoes
30
Fish
20
Chicken Meat
15

Margo's Grocery
Beans
20
Carrots
15
Apples
30

The two shops are separated by an empty line so that we can calculate values for each store.

I want to calculate the total revenue of products(the numbers beneath the product * value for a single item) of these shops and the number of items that were bought in total.

The problem I am having is that I don't know how to link the name of the items to the values below it. So Python needs to know that as it is reading each line it should know what value to multiply the number beneath it. For example a potato costs 0.70 for one piece so it should multiply 0.7 by 30 and so on for the different items.

This is what I have coded so far:

user = input("Enter file name - AprilSales, MaySales, or JuneSales")
revenue = 0
response = None

try:
    response = urllib.request.urlopen("link of server" + user + ".txt")
except:
    print("File not found")

fileData = response.read().splitlines()

for i in range(len(fileData)):
    fileData[i] = fileData[i].decode('utf-8')

for line in fileData:
     if len(line) != 0:
         #try block to only convert the strings which are able to be converted to ints and leave the rest
         try: 
              print(int(line))
         except:
              print(line)
              if(line == "Potatoes"):
                  revenue = revenue + int(line.next() * 0.7)
              if(line == "Fish"):
                  revenue = revenue + int(line.next() * 1.50)
              if(line == "Chicken"):
                  revenue = revenue + int(line.next() * 1.70)
      else:
        break

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

芸娘子的小脾气 2025-02-11 14:41:34

我们可以使用itertools模块来帮助我们处理文件,因为它们是由黑线分开的,因此

>>> import itertools
>>> text="""Jo's Deli Express
Potatoes
30
Fish
20
Chicken Meat
15

Margo's Grocery
Beans
20
Carrots
15
Apples
30"""
>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        print(key, list(group))

    
True ["Jo's Deli Express", 'Potatoes', '30', 'Fish', '20', 'Chicken Meat', '15']
False ['']
True ["Margo's Grocery", 'Beans', '20', 'Carrots', '15', 'Apples', '30']

>>>

首先我们绘制了线条,我们会剥离每条线(以确保空行真的很空,没有那里有一些偷偷摸摸的空间,并从一个偷偷摸摸的空间中删除了一个不必要的空白空间,然后将其放入一个衬里,我们可以使用 map ),然后使用 groupby 将其拆分在黑线上。

现在,我们只需要处理每个组中的每个组,鉴于结构现在为[store_name,product1,narter1,produc2,nose2,...,...,生产,金额],我们只需要构建一种方便的方法来处理它,然后打包该功能成为一个函数。

但首先让 dictionary 现在,要将它们全部放在整洁的小地方,并从一个无尽的IF-Else Cascade中撕下撕裂,

prices = {"Potatoes": 0.7,
          "Fish":1.50,
          "Chicken":1.70,
          "Beans": 2, 
          "Carrots": 1.5, 
          "Apples": 3,
          ...
         }

现在让我们现在可以构建该功能

def process_data(data):
    name, *products_data = data
    it = iter(products_data)
    revenue = 0
    products={}
    for prod, amount in zip(it, it):
        amount = int(amount)
        revenue += prices.get(prod,0) * amount #by using the .get method we avoid getting a KeyError exception
        products[prod] = products.get(prod,0) + amount #and in case of a repeat we wouldn't overwrite it
    return name, revenue, products

     

,我们可以将我们超越该功能的组馈送

>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        if not key:
            continue
        print(process_data(group))

    
("Jo's Deli Express", 51.0, {'Potatoes': 30, 'Fish': 20, 'Chicken Meat': 15})
("Margo's Grocery", 152.5, {'Beans': 20, 'Carrots': 15, 'Apples': 30})
>>> 

,现在您可以将其保存在其他数据结构中现在

>>> stores_data={}
>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        if not key:
            continue
        store,revenue,prod = process_data(group)
        stores_data[store]={"revenue": revenue, "products":prod}
 
        
>>> stores_data
{"Jo's Deli Express": {'products': {'Chicken Meat': 15,
                                    'Fish': 20,
                                    'Potatoes': 30},
                       'revenue': 51.0},
 "Margo's Grocery": {'products': {'Apples': 30, 'Beans': 20, 'Carrots': 15},
                     'revenue': 152.5}}
>>> 

,所有内容都已包装和处理,询问全球收入很容易

>>> sum(x["revenue"] for x in stores_data.values())
203.5
>>> 

知道特定商店中有多少商店出售了

>>> for store, data in store_data.items():
        print(store, sum(data["products"].values()))

    
Jo's Deli Express 65
Margo's Grocery 65
>>> 

it = iter(products)zip(zip)它,它)具有以下效果:

>>> a=range(10)
>>> it=iter(a)
>>> list(zip(it,it))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>>

iter制作事物的迭代器,那是我们想要的东西的一次,

>>> it=iter(a)
>>> list(it)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it)
[]
>>> 

所以当zip消耗时,它不会达到同一元素再次使其与下一个元素与下一个元素配对,如果不是这种情况,

>>> list(zip(a,a))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> 

我们可以替换products process_data中的 counter 您无需使用。对于读者

we can use the itertools module to help us process the file, given that they are separated by a black line like so

>>> import itertools
>>> text="""Jo's Deli Express
Potatoes
30
Fish
20
Chicken Meat
15

Margo's Grocery
Beans
20
Carrots
15
Apples
30"""
>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        print(key, list(group))

    
True ["Jo's Deli Express", 'Potatoes', '30', 'Fish', '20', 'Chicken Meat', '15']
False ['']
True ["Margo's Grocery", 'Beans', '20', 'Carrots', '15', 'Apples', '30']

>>>

first we get the lines, we strip each one (to make sure that the empty line is really empty and doesn't have some sneaky space there, and remove unnecessary white space from the others one too, and to make that into a one liner we can use a map), then use groupby to split that on the on black line.

Now we just need to process each of those groups, given that the structure is now [store_name, produc1,amount1, produc2,amount2, ..., producn,amountn] we just need to build a convenient way to handle that, and pack that into a function.

But first let make a dictionary with all those prices to have them all in neat little place and get rip off an endless if-else cascade

prices = {"Potatoes": 0.7,
          "Fish":1.50,
          "Chicken":1.70,
          "Beans": 2, 
          "Carrots": 1.5, 
          "Apples": 3,
          ...
         }

now lets build that function

def process_data(data):
    name, *products_data = data
    it = iter(products_data)
    revenue = 0
    products={}
    for prod, amount in zip(it, it):
        amount = int(amount)
        revenue += prices.get(prod,0) * amount #by using the .get method we avoid getting a KeyError exception
        products[prod] = products.get(prod,0) + amount #and in case of a repeat we wouldn't overwrite it
    return name, revenue, products

     

now we can feed the groups we get above to this function

>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        if not key:
            continue
        print(process_data(group))

    
("Jo's Deli Express", 51.0, {'Potatoes': 30, 'Fish': 20, 'Chicken Meat': 15})
("Margo's Grocery", 152.5, {'Beans': 20, 'Carrots': 15, 'Apples': 30})
>>> 

and now in turn you can you can save it in another data structure like a dictionary yet again

>>> stores_data={}
>>> for key,group in itertools.groupby(map(str.strip,text.splitlines()), bool):
        if not key:
            continue
        store,revenue,prod = process_data(group)
        stores_data[store]={"revenue": revenue, "products":prod}
 
        
>>> stores_data
{"Jo's Deli Express": {'products': {'Chicken Meat': 15,
                                    'Fish': 20,
                                    'Potatoes': 30},
                       'revenue': 51.0},
 "Margo's Grocery": {'products': {'Apples': 30, 'Beans': 20, 'Carrots': 15},
                     'revenue': 152.5}}
>>> 

Now that everything is packed and processed, asking for the global revenue is simple

>>> sum(x["revenue"] for x in stores_data.values())
203.5
>>> 

to know how many items in total a particular store sold

>>> for store, data in store_data.items():
        print(store, sum(data["products"].values()))

    
Jo's Deli Express 65
Margo's Grocery 65
>>> 

the it = iter(products), zip(it, it) have the following effect:

>>> a=range(10)
>>> it=iter(a)
>>> list(zip(it,it))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>>

iter make an iterator of the thing, that is a one time only iterable of the thing

>>> it=iter(a)
>>> list(it)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it)
[]
>>> 

which we want so when zip consume it wouldn't hit the same element again making it possible to pair it with the next one, if that weren't the case we would get

>>> list(zip(a,a))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> 

You can replace the products dict in process_data for a Counter so you don't need to use .get method, but I leave that as an exercise for the reader

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文