从python中的txt文件中提取特定数据
我有一个从python中的txt文件中提取特定数据,python,python-3.x,file-handling,Python,Python 3.x,File Handling,我有一个.txt文件(update.txt),其中记录了我对程序所做的更新更改。内容如下: make Apples 4 make Oranges 3 outstanding Bananas 1 restock Strawberries 40 restock Pineapples 23 如何根据我选择的选项适当打印(例如,我只想打印所有“重新进货”数据)。输出应如下所示: 0-restock, 1-make, 2-outstanding. Enter choice: 0 Summarised D
.txt
文件(update.txt
),其中记录了我对程序所做的更新更改。内容如下:
make Apples 4
make Oranges 3
outstanding Bananas 1
restock Strawberries 40
restock Pineapples 23
如何根据我选择的选项适当打印(例如,我只想打印所有“重新进货”数据)。输出应如下所示:
0-restock, 1-make, 2-outstanding. Enter choice: 0
Summarised Data for RESTOCK ***
Strawberries 40
Pineapples 23
下面的代码是正确的方法吗
choice = int(input("0-restock, 1-make, 2-outstanding. Enter choice: "))
if choice == 0:
print("Summarised Data for RESTOCK ***")
with open("update.txt") as openfile:
for line in openfile:
for part in line.split():
if "restock" in part:
print(f"{fruitType} {quantity}")
最后一个循环是有问题的
choice=int(输入(“0-重新进货,1-制造,2-未完成。输入选项:”)
如果选项==0:
打印(“补货汇总数据***”)
打开(“update.txt”)作为打开文件:
对于openfile中的行:
动作、结果、数量=行。拆分()
如果操作==“重新进货”:
打印(f“{水果}{数量}”)
但是,我建议您对此类数据使用csv,它比这样的文本文件更合适。您的代码在第二行有缩进错误。此外,它没有定义
水果类型
和数量
,因此不会打印它们
除此之外,您还硬编码了“重新进货”选项,因此您的代码只能打印该选项的值。如果要以这种方式实现,则必须对每个可能的选项重复相同的代码
相反,您可以定义一个包含所有可能选项的字典,然后使用所选键(options[choice]
)动态打印相应的消息和文件中的相应值
这很容易扩展到新选项。只需将另一个键值对添加到字典中
完整示例:
选项={0':“重新进货”,
“1”:“make”,
“2”:“未完成”}
打印('选项:')
对于option,options.items()中的值:
打印(f'{option}:{value}')
选择=输入('输入选择:')
打印({options[choice].upper()}***'的f'摘要数据)
以open('update.txt')作为openfile:
对于openfile中的行:
动作、结果、数量=行。拆分()
如果操作==选项[选择]:
打印(f'{fruit}{quantity}')
输出:
Options:
0: restock
1: make
2: outstanding
Enter choice: 0
Summarised Data for RESTOCK ***
Strawberries 40
Pineapples 23
或
或
不,代码有一个明显的缩进错误。我的讲师没有教我们csv。仅使用txt。文件
Summarised Data for MAKE ***
Apples 4
Oranges 3
Summarised Data for OUTSTANDING ***
Bananas 1
def getdata(c):
choice_map = {"0": "restock", "1": "make", "2": "outstanding"}
s = open("update.txt", "r").read()
print("Summarised Data for RESTOCK ***\n ")
for i in s.split("\n"):
if choice_map[str(c)] in i:
print(i.replace(choice[str(c)], "").strip())
choice = int(input("0-restock, 1-make, 2-outstanding. Enter choice: "))
getdata(choice)