如何根据产品输入从txt文件中准确定价?

How to exact price from txt file based on the product input?

我是 python 的新手,无法解决这个问题(我已经进行了广泛搜索)

我的目标是完成一个购物程序,用户在该程序中输入产品,程序然后读取相关的 txt 文件和 returns 商品价格。

这是我当前的代码:

product_name_input = str(input("Please enter products name: "))

with open("products.txt") as text_file:    

    p_name  = [str(line.split(", ")[1]) for line in text_file]
    p_price = [float(line.split(", ")[2]) for line in text_file]

    while True:
        p_name == product_name_input
        print(p_price)
        break

    if product_name_input not in p_name:
        print("That product does not exist")

如果文件中确实存在作为输入的产品,我得到的当前输出:

Please enter products name: shirt

[]

如果文件中不存在输入的产品,我得到的当前输出:

Please enter products name: freezer

[]

That product does not exist

非常感谢对此的任何帮助!

这一行是一个好的开始:

with open("products.txt") as text_file:   

它创建一个打开文件的句柄(使用带有 with 的上下文管理器,这是一个好习惯)。您可以遍历变量 text_file 以从文件中获取每一行,一次一行。但是,如果不将文件句柄重置为文件开头,您只能执行一次。

所以在这段代码中:

    p_name  = [str(line.split(", ")[1]) for line in text_file]
    p_price = [float(line.split(", ")[2]) for line in text_file]

第一行完全耗尽文件,第二行导致空列表,因为文件中没有更多行可读。

一种方法是遍历文件一次,但同时构建两个列表:

p_name = []
p_price = []
with open("products.txt") as text_file:
    for line in text_file:
        p_name.append(str(line.split(", ")[1]))
        p_price.append(float(line.split(", ")[2]))

一个可以说更 pythonic,但可能更难理解的解决方案:

with open("products.txt") as text_file:
    p_name, p_price = zip(*[
        (str((parts := line.split(", "))[1]), float(parts[2]))
        for line in text_file
    ])

可读性很重要,所以您可能更喜欢第一种解决方案。第二种解决方案在某些情况下可能更好,但我认为您现在不太关心这个问题。

第二种方案有什么不同:

  • 一次创建所有结果,无需设置
  • 该行仅拆分一次,结果重新用作 parts
  • 结果收集在元组列表中,然后使用列表中的 zip() 将其分成您需要的两个列表(使用 * 解压)

所有这些都是假设您实际上对第一列不感兴趣,因为 [1] 是第二列,而 [2] 是第三列。

如果您的文本文件包含带分隔字符串的行,请考虑使用 csv module

import csv

product_name_input = str(input("Please enter products name: "))

with open("products.txt") as text_file:    
    lines = csv.reader( text_file, delimiter=',' )
    for line in lines:
        p_name, p_price = line
        if p_name == product_name_input:
           print(p_price)
           break # found
        print("That product does not exist")

在下面的行中,text_file 被读取为一个可迭代对象,一旦其中的所有项目都被访问就变成空的

p_name  = [str(line.split(", ")[1]) for line in text_file]

更好的方法是将所有行读入一个列表变量,然后从那里处理它们。理想情况下构建一个 name:price 对的字典,然后查询字典以获取产品名称的价格。

product_name_input = str(input("Please enter products name: "))

with open("products.txt") as text_file:

    lines = text_file.readlines()

name_price_dict  = {str(line.split(", ")[1]):float(line.split(", ")[2]) for line in lines}

query_price = name_price_dict.get(product_name_input)

if query_price is not None:
    print(f"Price for {product_name_input} is {query_price}")
else:
    print(f"Price for {product_name_input} not found")