2015-05-04 69 views
-1

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

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

项目,价格和年龄的

杂牌。

我还需要创建两个搜索。

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

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

  • 搜索由年龄。一旦程序找到这些项目,就需要根据价格打印清单 - 从最低价格到最高价格。
  • 例如,您输入的年龄15 - 30,程序打印出适当的 项目,并通过价格排序。

    任何帮助将是很好的。至少从我可以从哪里开始。 谢谢。


    EDITED


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

    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.") 
    
    +0

    那么,你可能需要一个'for'循环,比较'=='或'项[ ],正如Will所指出的那样,并且从像这样完成的文件中读取:'用inFile:records = inFile.readlines()'打开(“myFileName.txt”,“r”)。 '记录'将包含文件中的所有行,即' - 项目的名称,价格和年龄。 –

    +0

    name_search在您的示例中用作变量和函数名称。其中一个会覆盖另一个 – Will

    +0

    我错误地翻译了这个程序。在我的原始代码中,变量和函数的名称是不同的。就像我刚才提到的那样,它表示for循环出现错误。我无法理解为什么:| –

    回答

    0

    如果你想翅片它通常是作为简单的列表的东西如:

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

    然而,在你的情况下,搜索列表是列表的列表,所以你需要“项目“不知何故。列表理解通常是最容易理解的,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']) 
    
    +0

    在C++中,我是这样做的结构。用“名称,价格和年龄”来拒绝该项目。在这里可以做类似的事吗? o.o因为关于物品的细节需要“卡在一起”。 –

    +0

    是的。有几种方法。创建一个班级或使用命名元组 – Will

    +0

    感谢您的启动。它真的帮助了我! –