gpt4 book ai didi

python - 如何统计文本文件中重复单词的数量?

转载 作者:行者123 更新时间:2023-12-01 09:06:51 25 4
gpt4 key购买 nike

自动售货机程序的代码示例

item = int(input("What item do you want: [1-10]"))
item_chosen = open("items.txt","a")
item_chosen.write(str(item))
item_chosen_data = items_chosen.read()
item_chosen.close()

从这里,我如何能够检查文本文件中存储了每个商品编号的数量(因为自动售货机在商品“不可用”之前应该只有有限的库存)?

最佳答案

item = int(input("What item do you want: [1-10]"))

# use the with open structure to work with files without having to explicitly close them
with open("items.txt","a+") as item_chosen:
item_chosen.write(str(item))
item_chosen_data = item_chosen.read()

# Use the string.split() method to get the item_chosen_data as a list instead of a string.
item_chosen_data = item_chosen_data.split()

# Create a set from the list of items, the removes duplicate values.
unique_items = set(item_chosen_data)

# Initialize a dictionary to map each item to it's count.
item_to_count = {}

# for each unique item
for item in unique_items:
# map the item to the number of times it appears in the list (ie. list.count() method)
item_to_count[item] = item_chosen_data.count(item)

我希望我所做的评论是不言自明的,但如果需要更多信息,请告诉我。本质上,您希望将从文本文件中读取的信息分解为列表,这允许您使用 list.count() 方法。

此外,就像其他人提到的那样,在此任务中完全避免写入文件可能是有益的。另一种方法是定义一个字典,其中包含自动售货机中每个商品的编号,例如:

# build a dictionary mapping each item to it's stock
item_to_stock = {'coke': 3, 'pepsi': 2, 'apple_juice': 5, 'doritos': 3}

# put a coke into the vending machine:
item_to_stock['coke'] = item_to_stock.get('coke', 0) + 1

# take a pepsi out of the vending machine, first check if the item is in stock
if item_to_stock.get('pepsi') > 0:
item_to_stock['pepsi'] = item_to_stock['pepsi'] - 1

关于python - 如何统计文本文件中重复单词的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com