703 views|5 replies

336

Posts

2

Resources
The OP
 

"Python Programming Quick Start to Automate Tedious Work 2nd Edition" Part 2 Automation Tasks Chapters 8-20 [Copy link]

" Python Programming Quick Start to Automate Tedious Work 2nd Edition" Part 2 Automation Tasks
——Reflections after reading Chapters 8 to 20
The second part of the book is an introduction to advanced applications based on the basic knowledge in the first part, which is also the focus of the book. This part mainly includes regular expressions, input validation, file processing (basic file reading and writing, Excel spreadsheet file operations, Google spreadsheet operations, CSV file operations, JSON data processing, PDF file operations, word file operations), email sending and receiving, graphic image processing, etc.
This section introduces the content in detail, starting from the perspective of practical projects, introducing the meaning and usage of the methods contained in each module, and comparing the application objects and application scope of similar methods. The following is a mind map starting from Chapter 8.

Figure 1 Mind map of Chapter 8 to Chapter 12

Figure 2 Mind map of Chapter 13 to Chapter 17

Figure 3 Mind map of Chapter 18 to Chapter 20.
Chapter 8 Exercises
1. Does PyInputPlus come with the Python standard library?
answer:
PyInputPlus is not a standard library that comes with Python and needs to be installed through pip.
2. Why is PyInputPlus usually imported using import pyinputplus as pyip?
answer:
This can make code entry more concise.
3. What is the difference between inputInt() and inputFloat()?
answer:
The InputInt() method returns an integer; the inputFloat() method returns a floating-point number.
4. How do you use PyInputPlus to ensure that users enter integers between 0 and 99?
answer:
PyInputPlus.inputint(min=0, max=99)
5. What is passed into the allowRegexes and blockRegexes keyword arguments?
answer:
Displays a list of regex strings that are allowed or denied.
6. What will inputStr(limit=3) do if three blanks are entered?
answer:
Throws a RetryLimitException.
7. What will inputStr(limit=3, default='hello') do if 3 blanks are entered?
answer:
Returns the string 'hello'.
Chapter 9 Exercises
1. What is the relative path relative to?
answer:
Relative paths are relative to the current working directory.
2. Where does the absolute path start?
answer:
Start in the root folder, such as C:\
3. On Windows operating systems, what is the result of evaluating Path('C:/Users')/'Al'?
answer:
On Windows the result is 'C:/Users/Al'.
4. On Windows, what is the result of evaluating 'C:/Users' / 'Al'?
answer:
will go wrong.
5. What do the os.getcwd() and os.chdir() functions do?
answer:
The os.getcwd() function returns the current working directory. The os.chdir() function changes the current working directory.
6. What are the . and .. folders?
answer:
The . folder is the current folder, and the .. folder is the parent folder of the current folder.
7. In C:\bacon\eggs\spam.txt, which part is the directory name and which part is the base name?
answer:
C:\bacon\eggs\ is the directory name and spam.txt is the base name.
8. What are the three “mode” parameters that can be passed to the open() function?
answer:
Parameter 'r' corresponds to read mode, 'w' corresponds to write mode, and 'a' corresponds to append mode
9. What happens if an existing file is opened in write mode?
answer:
The file contents are deleted and overwritten.
10. What is the difference between the read() and readlines() methods?
answer:
read() reads all the contents of the file as strings, and readlines() returns a list of strings by line of the current file content.
11. What data structure is the shelf value similar to?
answer:
A shelf is similar to a dictionary, with keys and values.
Chapter 10 Exercises
  1. What is the difference between shutil.copy() and shutil.copytree()?
    Answer:
    shutil.copy() function will copy a file, whereas shutil.copytree() will copy an entire folder along with all its contents.
  2. What function is used to rename files?
    Answer:
    shutil.move() function is used to rename files and move files.
  3. What is the difference between send2trash and the delete function in shutil module?
answer:
The delete function in the send2trash module moves a file or folder to the trash, while the delete function in the shutil module permanently deletes files and folders.
4. The ZipFile object has a close() method, just like the File object's close() method. What method of the ZipFile object is equivalent to the File object's open() method?
answer:
The Zipfile.ZipFile() function is equivalent to the open() function. The first parameter is the file name and the second parameter is the mode for opening the ZIP file (read, write, or append).
Chapter 11 Exercises
  1. Write an assert statement that triggers an AssertionError if the variable spam is an integer less than 10.
    Answer:
    assert spam >= 10,'spam is less than 10'.
  2. Write an assert statement that triggers an AssertionError if eggs and bacon contain the same case-insensitive strings (that is, 'hello' and 'hello' are considered the same, and 'goodbye' and 'GOODbye' are also considered the same).
    Answer:
    assert eggs.upper() != bacon.upper(), 'The eggs and bacon are the same!'.
  3. Write an assert statement that always triggers an AssertionError.
    Answer:
    assert false, 'this always act'.
  4. In order to call logging.debug(), which two lines of code must be added to the program?
    Answer:
    import logging
    logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
  5. In order for logging.debug() to send log messages to a file called programLog.txt, which two lines of code must be added to the program?
    Answer:
    import logging
    logging.basicConfig(filename='programLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
  6. What are the 5 log levels?
    Answer:
    The log levels are: DEBUG, INFO, WARNING, ERROR and CRITICAL.
  7. Which line of code could you add to disable all logging messages in your program?
    Answer:
    logging.disable (logging.CRITICAL)
  8. Why is it better to use log messages than print() to display the same message?
    Answer:
    In programming, there is no need to delete log information, just disable it, which reduces the workload of software design.
  9. What is the difference between the Step Over, Step In, and Step Out buttons in the debug control window?
    Answer:
    Step over executes a function; step in enters a function; step out quickly executes subsequent code until you exit the current function.
  10. When does the debugger stop after you click the Continue button?
    Answer:
    It continues to run the program until power is lost or the program ends.
  11. What is a breakpoint?
    Answer:
    It tells the debugging system to pause execution at the current line of the breakpoint.
  12. In Mu, how do I set a breakpoint on a line of code?
answer:
Click a row number.
Chapter 12 Exercises
  1. Briefly describe the differences between the webbrowser, requests, BeautifulSoup, and selenium modules.
    Answer:
    The webbrowser module has an open() method that starts a web browser and opens a specified URL. The requests module can download files and pages from the Internet. The BeautifulSoup module parses HTML. The selenium module can start and control a browser.
  2. What type of object does requests.get() return? How do I access the downloaded content as a string?
    Answer:
    The requests.get() function returns a Response object, which has a text attribute containing the string of the downloaded content.
  3. Which requests method is used to check whether the download was successful?
    Answer:
    If there is a problem with the download, the raise_for_status() method will throw an exception; if the download is successful, it will do nothing.
  4. How to get the HTTP status code of requests response?
    Answer:
    The status_code attribute of the Response object contains the HTTP status code.
  5. How to save the requests response to a file?
    Answer:
    After opening a new file on your computer in "binary write" mode, use a for loop to iterate through the iter_content() method of the Response object and write each segment to the file.
  6. What is the shortcut key to open the browser's developer tools?
    Answer:
    F12
  7. In the developer tools, how do I view the HTML of a specific element on the page?
    Answer:
    Select Inspect Element from the menu
  8. To find the element with the id attribute main, what is the CSS selector string?
    Answer:
    '#main'
  9. To find elements with the CSS class highlight, what is the CSS selector string?
    Answer:
    '.highlight'
  10. To find all elements within an element, what is the CSS selector string?
    Answer:
    'div div'
  11. To find an element whose value attribute is set to favorite, what is the CSS selector string?
    Answer:
    'button[value="favorite"]'
  12. Suppose you have a Beautiful Soup Tag object stored in the variable spam, and the element you are looking for is Hello, world!. How do you get the string 'Hello world!' from this Tag object?
    Answer:
    spam.getText()
  13. How do I save all the attributes of a Beautiful Soup Tag object into the variable linkElem?
    Answer:
    linkElem.attrs
  14. Running import selenium has no effect. How do I import the selenium module correctly?
    Answer:
    from selenium import webdriver
  15. What is the difference between the find_element_* and find_elements_* methods?
    A:
    The find_element_* methods return the first matching element as a WebElement object. The find_elements_* methods return all matching elements as a list of WebElement objects.
  16. What methods does Selenium's WebElement object have to simulate mouse clicks and keyboard key presses?
    Answer:
    click() and send_keys()
  17. You can call send_keys(Keys.expression ENTER) on the WebElement object of the Submit button, but is there an easier way to submit a form using Selenium?
    Answer:
    Calling the submit() method will submit the form
  18. How to use Selenium to simulate clicking the browser's "Forward", "Back" and "Refresh" buttons?
answer:
WebDriver object methods such as forward(), back(), and refresh()
Chapter 13 Exercises
For the following questions, imagine that you have a Workbook object stored in the variable wb, a Worksheet object stored in sheet, a Cell object stored in cell, a Comment object stored in comm, and an Image object stored in img.
  1. What does the openpyxl.load_workbook() function return?
    Answer:
    The openpyxl.load_workbook() function returns a Workbook object
  2. What does the workbook property wb.sheetnames return?
    Answer:
    The sheetnames property returns a Worksheet object.
  3. How to get the Worksheet object of the worksheet named 'Sheet1'?
    Answer:
    wb['Sheet1']
  4. How to get the Worksheet object of the active worksheet of a workbook?
    Answer:
    wb.active
  5. How do I get the value in cell C5?
    Answer:
    sheet.cell(row=5,column=3).value
  6. How do I set the value in cell C5 to "Hello"?
    Answer:
    sheet.cell(row=5,column=3).value="Hello"
  7. How to get the integers representing the row and column of a cell?
    Answer:
    cell.row
    cell.column
  8. What do the worksheet properties sheet.max_column and sheet.max_row return? What are the types of these properties?
    Answer:
    They return the integer value of the maximum number of columns and rows in the table, which is an integer.
  9. If you want to get the integer index of column 'M', what function do you need to call?
    Answer:
    openpyxl.cell.column_index_from_string('M')
  10. If you want to get the string name of column 14, what function do you need to call?
    Answer:
    openpyxl.cell.get_column_letter(14)
  11. How to get a tuple of all Cell objects from A1 to F1?
    Answer:
    sheet['A1':'F1']
  12. How to save the workbook file name as example.xlsx?
    Answer:
    wb.save('example.xlsx')
  13. How to set a formula in a cell?
    Answer:
    The formula setting is the same as the value, and needs to be preceded by a formula string of "=".
  14. If you need to get the result of a formula in a cell, rather than the formula itself, what must you do first?
    Answer:
    When using load_workbook(), set the data_only keyword to True.
  15. How do I set the height of row 5 to 100?
    Answer:
    sheet.row_dimensions[5].height = 100
  16. How do I set the width of column C?
    Answer:
    Use sheet.column_dimensions['C'].width to set the column width.
  17. What is frozen panes?
    Answer:
    Use sheet.freeze_panes method to freeze panes.
  18. Which 5 functions and methods do you need to call to create a bar chart?
answer:
openpyxl.charts.Reference(), openpyxl.charts.Series(), openpyxl.charts.BarChart(), chartObj.append(seriesObj) and add_chart()
Chapter 15 Exercises
  1. You cannot pass a string containing the name of a PDF document to the PyPDF2.PdfFileReader() function. What should you pass to the function?
    Answer:
    Pass the File object returned by open()
  2. In what mode should the File object required by PdfFileReader() and PdfFileWriter() be opened?
    Answer:
    Use read binary ('rb') for PdfFileReader() and write binary ('wb') for PdfFileWriter()
  3. How to get the Page object of page 5 from the PdfFileReader object?
    Answer:
    getPage(4)
  4. Which property of PdfFileReader stores the number of pages in the PDF document?
    Answer:
    The numPages variable in the PdfFileReader object
  5. If the PDF document represented by the PdfFileReader object is encrypted with the password swordfish, what should be done first to obtain a Page object from it?
    Answer:
    decrypt('swordfish')
  6. What method do you use to rotate the page?
    Answer:
    rotateClockwise() and rotateCounterClockwise(). The degree of rotation is passed as an integer parameter.
  7. What method returns the Document object of the document demo.docx?
    Answer:
    docx.Document('demo.docx')
  8. What is the difference between the Paragraph object and the Run object?
    Answer:
    Each Word document contains a list of Paragraph objects to represent paragraphs, and each Paragraph object contains a list of Run objects. Run objects are continuations of text in the same style.
  9. The doc variable holds a Document object. How do you get a list of Paragraph objects from it?
    Answer:
    doc.paragraphs
  10. Which type of object has the properties bold, underline, italic, strike, and outline?
    Answer:
    The Run object has these properties.
  11. What is the difference between setting the bold property value to True, False, or None?
    Answer:
    True always makes the Run object bold, and False always makes it not bold. None makes the Run object use the bold setting of the style.
  12. How to create a Document object for a new Word document?
    Answer:
    docx.Document()
  13. The doc variable holds a Document object. How do you add a paragraph with the text 'Hello there!'?
    Answer:
    doc.add_paragraph('Hello there!')
  14. Which integers represent the heading levels available in a Word document?
answer:
The integers 0, 1, 2, 3, and 4
Chapter 16 Exercises
  1. What features does Excel have that CSV does not?
    Answer:
    In Excel, spreadsheet values can be data types other than strings, cells can have different fonts, sizes, or colors, cells can have different widths and heights, adjacent cells can be merged, and images and charts can be embedded. CSV is only strings.
  2. What do we pass to csv.reader() and csv.writer() to create the reader and writer objects?
    Answer:
    The File object obtained through the open() method.
  3. For reader and writer objects, in what mode does the File object need to be opened?
    Answer:
    For reader objects, the File object needs to be opened in read binary mode ('rb'); for writer objects, it needs to be opened in write binary mode ('wb').
  4. What method takes a list argument and writes it to a CSV file?
    Answer:
    writerow()
  5. What are the delimiter and lineterminator keyword arguments used for?
    Answer:
    The delimiter argument changes the string used to separate cells in a row. The lineterminator argument changes the string used to separate rows.
  6. What function takes a string of JSON data and returns a Python data structure?
answer:
json.loads()
7. What function takes a Python data structure and returns a string containing the JSON data?
answer:
json.dumps()
Chapter 17 Exercises
  1. What is the UNIX epoch?
    Answer:
    The "UNIX epoch" is a time often referenced in programming: 00:00, January 1, 1970, Coordinated Universal Time (UTC).
  2. What function returns the number of seconds since the UNIX epoch?
    Answer:
    time.time()
  3. How to make the program pause for exactly 5 seconds?
    Answer:
    time.sleep(5)
  4. What does the round() function return?
    Answer:
    It returns an integer rounded to the value passed in.
  5. What is the difference between a datetime object and a timedelta object?
    Answer:
    A datetime object represents a specific moment in time. A timedelta object represents a period of time.
  6. Use the datetime module to find out what day of the week January 7, 2019 is.
    Answer:
    datetime.datetime(2019, 1, 7).weekday()
  7. Suppose you have a function named spam(), how do you call this function in a separate thread and run the code in it?
    Answer:
    threadObj = threading.Thread(target=spam)threadObj.start()
  8. What should be done to avoid multi-threaded concurrency problems?
answer:
Do not use the same global variables between threads.
Chapter 18 Exercises
  1. What is the protocol for sending emails? What is the protocol for checking and receiving emails?
    Answer:
    SMTP is used for sending emails, and IMAP is used for receiving emails.
  2. Which 4 smtplib functions/methods must be called to log into the SMTP server?
    Answer:
    smtplib.SMTP(), smtpObj.ehlo(), smptObj.starttls(), and smtpObj. login()
  3. Which two imapclient functions/methods must be called to log into an IMAP server?
    Answer:
    imapclient.IMAPClient() and imapObj.login().
  4. What parameters should be passed to imapObj.search()?
    Answer:
    Pass in the IMAP search keyword string
  5. If your code receives the error message "got more than 10000 bytes", what should you do?
    Answer:
    Assign the variable imaplib._MAXLINE to a large integer.
  6. The imapclient module is responsible for connecting to the IMAP server and finding emails. What module is responsible for reading the emails collected by imapclient?
    Answer:
    The pyzmail module is responsible for reading the downloaded emails.
  7. What are the credentials.json and token.json files when using the Gmail API?
    Answer:
    The credentials.json and token.json files tell the ezgmail module which Google account to use when accessing Gmail.
  8. In the Gmail API, what is the difference between thread and message objects?
    Answer:
    message represents a message, thread represents an email
  9. How do you find emails with file attachments using ezgmail.search()?
    Answer:
    Include the text 'has:atttachment' in the string you pass to search()
  10. What 3 pieces of information do you need from Twilio before sending a text message?
answer:
You will need your Twilio account SID number, authentication ID, and your Twilio phone number.
Chapter 19 Exercises
  1. What is an RGBA value?
    Answer:
    An RGBA value is a tuple of 4 integers, each ranging from 0 to 255.
  2. How to use the pillow module to get the RGBA value of 'CornflowerBlue'?
    Answer:
    ImageColor.getcolor('CornflowerBlue', 'RGBA')
  3. What is a rectangle tuple?
    Answer:
    A rectangle tuple is a tuple of 4 integers: the x-coordinate of the left edge, the y-coordinate of the top edge, the width, and the height.
  4. Which function returns an Image object for an image file named zophie.png?
    Answer:
    Image.open('zophie.png')
  5. How to get the width and height of an Image object?
    Answer:
    imageObj.size
  6. What method would you call to get an Image object with a 100 pixel by 100 pixel image, excluding the lower left quarter?
    Answer:
    imageObj.crop((0, 50, 50, 50))
  7. After modifying the Image object, how do you save it as an image file?
    Answer:
    imageObj.save('new_filename.png')
  8. What module contains pillow's shape drawing code?
    Answer:
    ImageDraw module
  9. The Image object has no draw method. What kind of object does? How do I get this type of object?
answer:
ImageDraw object, can provide point(), line(), rectangle()
Chapter 20 Exercises
  1. How to trigger the failsafe of PyAutoGUI to stop the program?
    Answer:
    Move the mouse pointer to the upper left corner of the screen, that is, the coordinate (0, 0)
  2. What function returns the current resolution?
    Answer:
    pyautogui.size()
  3. What function returns the coordinates of the current position of the mouse pointer?
    Answer:
    pyautogui.position()
  4. What is the difference between the pyautogui.moveTo() and pyautogui.move() functions?
    Answer:
    The moveTo() function moves the mouse pointer to the absolute coordinates of the screen, while the move() function moves the mouse pointer relative to its current position.
  5. What function is used to drag and drop the mouse pointer?
    Answer:
    pyautogui.dragTo() and pyautogui.drag().
  6. What function do you call to input the string "Hello, world!" for you?
    Answer:
    pyautogui.typewrite('Hello, world!').
  7. How to simulate pressing a special key like the left key?
    Answer:
    pyautogui.typewrite() takes a list of key strings or a single string for a single key.
  8. How to save the current screen content as a graphic file and name it screenshot.png?
    Answer:
    pyautogui.screenshot('screenshot.png')
  9. What code can set each PyAutoGUI function to pause for two seconds?
    Answer:
    pyautogui.PAUSE = 2
  10. If you want to automate clicks and keystrokes in a web browser, should you use PyAutoGUI or Selenium?
    Answer:
    Use Selenium to control a web browser
  11. What makes PyAutoGUI error-prone?
    Answer:
    PyAutoGUI will blindly click and type
  12. How do I find the size of every window on the screen that has the text Notepad in its title?
    Answer:
    yautogui.getWindowsWithTitle('Notepad')
  13. How do I make the Firefox browser the active window, in front of every other window on the screen?
answer:
w = pyatuogui.getWindowsWithTitle('Firefox'), then run w.activate()

Latest reply

Just take a quick look and you'll be ready to go. . . . . . , whether it can be automated is not so easy. . .   Details Published on 2024-5-16 13:42
 
 

336

Posts

2

Resources
2
 
After reading this book, I personally feel that this book can not only be used as an introduction, but also as a method guide and tool query book.
 
 
 

731

Posts

4

Resources
3
 

The Python technical content shared by the host is very novel, detailed and well-organized, which successfully aroused my interest in this book.

 
 
 

145

Posts

0

Resources
4
 

Very comprehensive, chapters 8 to 20 are all about specific applications.

 
 
 

1129

Posts

1

Resources
5
 

Just take a quick look and you'll be ready to go. . . . . .

, whether it can be automated is not so easy. . .

 
 
 

336

Posts

2

Resources
6
 

The automation part should be re-read again in a targeted manner according to the needs of each person in actual work, which will be more meaningful.

 
 
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list