从 Python 中的 txt 文件读取商店列表

Reading shop list from txt file in Python

我对 Python 很陌生,需要帮助从 txt 文件中读取信息。我有一个大型 C++ 应用程序需要在 Python 中复制它。可悲的是,我不知道从哪里开始。我一直在阅读和观看一些教程,但从他们那里得到的帮助很少,我 运行 没时间了。

所以我的任务是: 我有一个购物清单:

-Name of the item, price and age.

我还需要创建两个搜索。

  1. 搜索商品是否在商店中(比较字符串)。

if name of the item is == to the input name.

  1. 年龄搜索。一旦程序找到了物品,它就需要根据价格打印清单——从最低价到最高价。

For example you input age 15 - 30, the program prints out appropriate items and sorts them by the price.

任何帮助都会很好。至少从我可以开始的地方。 谢谢。


已编辑


到目前为止,我有这个代码:

class data:
    price = 0
    agefrom = 0
    ageto = 0
    name = ''

# File reading
def reading():
    with open('toys.txt') as fd:
        toyslist = []
        lines = fd.readlines()
        for line in lines:
            information = line.split()
            print(information)
            """information2 = {
                'price': int(information[1])
                'ageftom': int(information[2])
                'ageto': int(information[3])
                #'name': information[4]
            }"""
            information2 = data()
            information2.price = int(information[0])
            information2.agefrom = int(information[1])
            information2.ageto = int(information[2])
            information2.name = information[3]

            toyslist.append(information2)
    return toyslist

information = reading()

我对这部分有疑问。我想将用户的输入与txt文件中的商品信息进行对比

n_search = raw_input(" Please enter the toy you're looking for: ")

def name_search(information):
for data in information:
    if data.name == n_search:
print ("We have this toy.")
else:
    print ("Sorry, but we don't have this toy.")

如果你想在列表中找到一些东西,通常很简单:

if "apple" in ["tuna", "pencil", "apple"]

但是,在您的情况下,要搜索的列表是一个列表列表,因此您需要以某种方式 "project" 它。列表理解通常是最容易推理的,一种 for 循环中的 for 循环。

if "apple" in [name for name,price,age in [["tuna",230.0,3],["apple",0.50,1],["pencil",1.50,2]]]

从这里开始,您要查看过滤器,您可以通过过滤器提供一个函数来确定条目是否匹配。您可以在 for 循环中自己滚动或使用更实用的东西,例如 'itertools'.

对列表进行排序也很简单,如果需要,只需使用 'sorted(my_list)' 提供比较函数即可。


根据您的评论举例...

class ShoppingListItem:
   def __init__(self,name,price,age):
      self.name=name
      self.price=price
      self.age=age

from collections import namedtuple
sli = namedtuple("ShoppingListItem",['name','age','price'])