You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从文件获取字典单词索引及实现无硬编码商店程序?

问题解答

1. 如何从文件中获取dictionary内单词的索引?

首先得明确:Python 3.7及以上版本的字典会保留插入顺序,这时候“索引”才有实际意义(指单词作为键在插入序列中的位置)。如果是更早版本,字典是无序的,索引就没有参考价值了。

实现步骤如下:

  • 先把文件内容解析加载为字典
  • 将字典的键转换为列表(列表支持索引查找)
  • 用列表的index()方法获取目标单词的索引

示例代码:

# 从文件加载字典(假设文件每行格式为"单词:对应值")
word_dict = {}
with open("your_word_file.txt", "r") as f:
    for line in f:
        # 去除首尾空白后分割键值
        word, value = line.strip().split(":")
        word_dict[word] = value

# 获取目标单词的索引
target_word = "banana"
if target_word in word_dict:
    word_index = list(word_dict.keys()).index(target_word)
    print(f"单词「{target_word}」的索引是:{word_index}")
else:
    print(f"字典中未找到单词「{target_word}」")

2. 编写可动态加载商品的商店程序

你的现有代码会报错,原因是test.txt里的内容是一整行的banana:3 apple:4,直接按:分割会得到3个元素,无法解包到name和score两个变量里。另外,用with语句操作文件更安全(自动关闭文件),也更符合Python最佳实践。

修正后的完整代码:

# 动态加载商品和价格到字典
product_dict = {}
with open('test.txt', 'r') as f:
    # 读取文件内容,按空格分割成单个商品条目
    items = f.read().strip().split()
    for item in items:
        # 每个条目按冒号分割为名称和价格
        name, price_str = item.split(":")
        product_dict[name] = int(price_str)

# 商店交互逻辑(可按需扩展)
print("Welcome to my store! What would you like to do?")
while True:
    user_input = input("Enter a product name to check price, or 'quit' to exit: ").strip().lower()
    if user_input == 'quit':
        print("Thanks for visiting!")
        break
    if user_input in product_dict:
        print(f"The price of {user_input} is ${product_dict[user_input]}")
    else:
        print(f"Sorry, we don't have {user_input} in stock right now.")

关键优化点:

  • 用with语句管理文件,避免手动关闭文件可能带来的资源泄漏
  • 先按空格拆分所有商品条目,再逐个按冒号拆分键值,适配文件中商品同行或换行的情况
  • 完全动态解析文件内容,只要文件保持商品名:价格的格式(条目间用空格分隔),修改文件内容后程序无需任何改动即可正常运行

内容的提问来源于stack exchange,提问作者Noob Saibot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:23:57