从python中的txt文件中提取特定数据

时间:2021-03-02 14:37:57

标签: 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 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}")

3 个答案:

答案 0 :(得分:2)

您的代码在第二行有缩进错误。此外,它没有定义 fruitTypequantity,因此不会打印它们。

除此之外,您还对“restock”选项进行了硬编码,因此您的代码只能打印该选项的值。如果要以这种方式实现它,则必须为每个可能的选项重复相同的代码。

相反,您可以定义一个包含所有可能选项的字典,然后使用所选键 (options[choice]) 动态打印相应消息和文件中的相应值。

这很容易扩展到新选项。您只需将另一个键值对添加到字典中即可。

完整示例:


options = {'0': 'restock',
           '1': 'make',
           '2': 'outstanding'}

print('Options:')
for option, value in options.items():
    print(f'  {option}: {value}')
choice = input('Enter choice: ')

print(f'Summarised Data for {options[choice].upper()} ***')
with open('update.txt') as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == options[choice]:
            print(f'  {fruit} {quantity}')

输出:

Options:
  0: restock
  1: make
  2: outstanding
Enter choice: 0
Summarised Data for RESTOCK ***
  Strawberries 40
  Pineapples 23

Summarised Data for MAKE ***
  Apples 4
  Oranges 3

Summarised Data for OUTSTANDING ***
  Bananas 1

答案 1 :(得分:0)

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)

答案 2 :(得分:-1)

最后的循环有问题

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:
            action, fruit, quantity = line.split()
            if action == "restock":
                print(f"{fruit} {quantity}")
                        

不过我建议你使用csv来处理这种类型的数据,它比这样的文本文件更合适