简体   繁体   English

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

[英]extract specific data from txt file in python

I have a single .txt file ( update.txt ) that has records of update changes I've made to my program.我有一个.txt文件 ( update.txt ),其中记录了我对程序所做的更新更改。 The contents are as follows:内容如下:

make Apples 4
make Oranges 3
outstanding Bananas 1
restock Strawberries 40
restock Pineapples 23

How do I print out appropriately according to an option I choose (eg I just want to print out all the "restock" data).如何根据我选择的选项适当地打印出来(例如,我只想打印出所有“补货”数据)。 The output should be as such: output 应该是这样的:

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

Is the below code the correct way to do it?下面的代码是正确的方法吗?

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}")

Your code has an indentation error in the second line.您的代码在第二行有缩进错误。 Also, it does not define fruitType and quantity , so it won't print them.此外,它没有定义fruitTypequantity ,因此不会打印它们。

Apart from that, you have hardcoded the " restock " option, so that your code can only print the values for that.除此之外,您还对“ restock ”选项进行了硬编码,因此您的代码只能打印该选项的值。 You would have to repeat the same code for each possible option if you were to implement it in this way.如果您要以这种方式实现它,您将不得不为每个可能的选项重复相同的代码。

Instead, you can define a dictionary holding all your possible options and then use the chosen key ( options[choice] ) to dynamically print an according message and the respective values from the file.相反,您可以定义一个包含所有可能选项的字典,然后使用所选键( options[choice] )动态打印相应的消息和文件中的相应值。

This is easily extensible to new options.这很容易扩展到新选项。 You simply add another key-value-pair to the dictionary.您只需将另一个键值对添加到字典中。

Full example:完整示例:


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}')

Output: Output:

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

or或者

Summarised Data for MAKE ***
  Apples 4
  Oranges 3

or或者

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)

The final loop is problematic最后的循环有问题

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}")
                        

However I recommend that you use csv for this type of data, it is much more suitable than a text file like this但是我建议你使用 csv 来处理这种类型的数据,它比这样的文本文件更合适

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM