Python calculates the cost of books purchased by the whole class

As the Secretary of the League branch and the monitor, there are too many materials and data in the whole class. Although office software can solve many data processing problems, learning the major of programming itself should reflect the level of the major. In addition, it is necessary to count which students in the class buy which books and use office software to calculate each semester, which will consume a lot of time. I think, Compile a program to calculate the book cost of the whole class. After making statistics every semester, Python can directly calculate it by itself, which can save a lot of time.

I hope this small program can help you.

1, Preparatory work

First of all, of course, we have to obtain the book data purchased by the whole class, and then the program can read the data and calculate it.

Here I use xlsx file form (this program uses the form of reading Excel form).

Note: it must be ensured that the name is followed by the order of courses. The columns of names in column B and courses in column C can be different. (if it is different, it must be modified in the code, otherwise the program cannot read the data!!!)

 

2, Code phase

Now that you have the data, start Python program calculation.

1. Use of Library (xlrd)

It should be noted here that the libraries installed by pip by default are the latest version, while the latest version of xlrd does not support xlsx files. You need to return xlrd to version 1.2.0

import xlrd

If you have the latest version of xlrd library installed on your computer, you need to delete it first.

You can directly find the library file of xlrd and delete it. You can also use it in cmd:

pip uninstall xlrd

When installing the old version of xlrd, add parameters at the end of cmd:

pip install xlrd==1.2.0

2. Obtain data

def work_book():    # Get table object
    file = open("discount Book.txt", "w")
    resort = xlrd.open_workbook("Workbook 1.xlsx")    # File path
    sheet = resort.sheet_by_index(0)    # Get sheet object
    """
    Get the workbook name and the number of worksheet rows and columns
    """
    table = sheet.name    # Gets the name of the worksheet
    count_line = sheet.nrows    # Get the number of rows
    clos = sheet.ncols        # Get the number of columns
    print("Worksheet" + table, count_line, 'that 's ok', clos, 'column\n', end=" ")
    
    """
    If your name is not in your form B Column, the course books are not available C Column,
    It's the name A Column, where are the course books B Column, then the following
    Book name: sheet.row_values(i)[2]  Change 2 in to 1 or your corresponding number of name columns
    Python The cycle starts with 0 by default, such as 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9
    therefore A The column corresponds to 0, and so on.
    """

    for i in range(count_line):
        read_line_book = sheet.row_values(i)[2].split(",")        
        # Get the book name and split it with Chinese stop sign
        read_line_name = sheet.row_values(i)[1]
        # Get name
        file.writelines(read_line_name + ',' + ",".join(read_line_book) + "\n")
    file.close()
# work_book()    # When reading data, you need to delete the comment and call work_book()

The data here is saved in a custom text file.

Operation results:

Stored file contents:

Note here: each student will buy more, less and no (here refers to their own purchase).

3. Data processing

def File():
    file = open("discount Book.txt", "r")  # Open work_ Text file created in book
    txt = file.read()
    dic = {}    # Create a dictionary to correspond to personnel books
    for i in txt.split("\n")[1:]:
        new_txt = i.split(",")
        if new_txt[0] != "" or new_txt[-1] != "":
            del_txt = new_txt
            dic[del_txt[0]] = del_txt[1:]
    print(dic)  # Copy the read content to Sum() and start calculation
    file.close()
# File()

In the for loop here, because in work_ In book, we save the read data as a text file (Notepad opened in the above figure).

I can see that everyone's program has wrapped it, and what we need is to read everyone's name and the corresponding course, put it into the dictionary, and form the key (name) to the value (Book).

The output results are as follows (in the form of Dictionary):

4. Data calculation

Then we will copy the data from the above File() and save it to Sum().

The most important step, program calculation!!!

def Sum():      # Calculate personal amount
    lst = {
        '***': ['MySQL Database technology and project', 'Basic course of College Students' innovation and Entrepreneurship', 'linux Network operating system'],
        '***': ['MySQL Database technology and project', 'Basic course of College Students' innovation and Entrepreneurship', 'Huitong Workplace English']
            }

    """
    lst As a test calculated with a small amount of data, if the result is successfully calculated, use ls Calculate the book cost of the whole class
    """

    ls = {
        '***': ['MySQL Database technology and project', 'Basic course of College Students' innovation and Entrepreneurship', 'linux Network operating system'],
        '***': ['MySQL Database technology and project', 'Basic course of College Students' innovation and Entrepreneurship', 'Huitong Workplace English'],
    }
    """
    Set the amount setting parameter corresponding to each book to float Value, the starting value of each book is 0 yuan, with for Loop through the key pair values in the dictionary,
    Because the book content here is stored in the form of a dictionary, it is more convenient to calculate.
    """

    MySQL_book, MySQL_book_money, MySQL_book_sum = 'MySQL Database technology and project', float(34.20), float(0)
    Sinnovation_book, Student_innovation_money, Sinnovation_sum = 'Basic course of College Students' innovation and Entrepreneurship', float(30.32), float(0)
    Java_book, Java_book_money, Java_book_sum = "java Basic introduction", float(45.45), float(0)
    Linux_book, Linux_book_money, Linux_book_sum = "linux Network operating system", float(37.85), float(0)
    English_book, English_book_money, English_book_sum = "Huitong Workplace English", float(35.57), float(0)
    Politics_book, Politics_book_money, Politics_book_sum = "Newly compiled military course course in Colleges and Universities", float(30.25), float(0)
    NoSQL_book, NoSQL_book_money, NoSQL_book_sum = "NoSQL Database technology and Application", float(60.65), float(0)
    sum_book = float(0)
    # Sum here_ Book as every judgment operation

    w = open("Textbook statistics.txt", "w", encoding="UTF-8")

    """
    Each traversal cycle determines whether the person contains the corresponding book, and then calculates the personal book fee
    """

    for i in ls.items():
        for j in range(2):
            if len(i) != 0:
                if MySQL_book in i[j]:
                    MySQL_book_sum += (sum_book + MySQL_book_money)
                if Sinnovation_book in i[j]:
                    Sinnovation_sum += (sum_book + Student_innovation_money)
                if Java_book in i[j]:
                    Java_book_sum += (sum_book + Java_book_money)
                if Linux_book in i[j]:
                    Linux_book_sum += (sum_book + Linux_book_money)
                if English_book in i[j]:
                    English_book_sum += (sum_book + English_book_money)
                if Politics_book in i[j]:
                    Politics_book_sum += (sum_book + Politics_book_money)
                if NoSQL_book in i[j]:
                    NoSQL_book_sum += (sum_book + NoSQL_book_money)
        count = "{}Books purchased{}\n Personal amount(Discounted price):{:.2f}element\n".format(
                        i[0], i[1], MySQL_book_sum + Sinnovation_sum + NoSQL_book_sum +
                        Linux_book_sum + Java_book_sum + Politics_book_sum + English_book_sum
                                                                                                        )
        print(count)
        MySQL_book_sum, \
        Sinnovation_sum,\
        NoSQL_book_sum,\
        Linux_book_sum,\
        Java_book_sum,\
        Politics_book_sum,\
        English_book_sum = float(0), float(0), float(0), float(0), float(0), float(0), float(0)
        w.writelines(count)
# Sum()

Output result:

And will create a text file that has calculated the book cost in the directory of the program.

Keywords: Python

Added by alsinha on Sat, 26 Feb 2022 05:20:34 +0200