r/inventwithpython • • May 14 '19

Beautiful soup

3 Upvotes

Hello,

I am trying the beautiful soup module in lesson 40. When I raise for status I get that error, even though I am following the steps Al shows. Replies on stack mention I should import a header? Why is that and why is it working in the video?

>>> res.raise_for_status()

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

res.raise_for_status()

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 940, in raise_for_status

raise HTTPError(http_error_msg, response=self)

requests.exceptions.HTTPError: 503 Server Error: Service Unavailable for url: https://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994


r/inventwithpython • • May 08 '19

Cracking Codes with Python

3 Upvotes

When i Answered Chapter one Practice questions , i found that my answer different from the answers on https://nostarch.com/crackingcodesanswers, i am sure that i answered them right, could anyone has read the book find the same ?


r/inventwithpython • • Apr 28 '19

How can filename.endswith('rxt') print texts ending with 'txt'?

3 Upvotes

Question from chapter 9, or video 33:

How does the line

if filename.endswith('rxt'):

print(filename)

detects filenames that end with 'txt'? Is endswith non greedy (if I use the right terminology?)


r/inventwithpython • • Mar 21 '19

ATBS Ch 6 Exercise Answer

3 Upvotes

Hi everyone,

First post to this forum, excited new convert to Python!

I struggled with this for a few days, but have got something I am pretty happy with. Thank to a lot of help and advice to Stack Exchange, I have to add. But, I put it all together myself, so I am proud:

from itertools import zip_longest

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]


def printlist(data_in):
    col_2 = [len(max(l2, key=len)) for l2 in data_in]
    rows = (list(zip_longest(*data_in)))
    i = 0
    for i in range(len(data_in)):
        print(str(rows[i][0]).rjust(col_2[0]), str(rows[i][1]).rjust(col_2[1]), str(rows[i][2]).rjust(col_2[2]))
        i += 1


printlist(tableData)

Any thoughts on if it could be improved? The only thing that I have not worked out/added in is if there were additional columns needing to be added automatically.

Cheers!


r/inventwithpython • • Aug 17 '18

Pandas or openpyxl?

3 Upvotes

I'm a tad confused between tehe two-pandas and openpyxl. I've had some experience using pandas before I got a hold of Automate The Boring Stuff with Python and I've just bumped into the Excel chapter. Can someone please give me some guidance?Should I stick to learning more on Pandas or move to openpyxl or intergrate the two?


r/inventwithpython • • Jul 05 '18

Ch12 Automate the boring stuff with Python

3 Upvotes

I have reached the section where I am writing the population census to the census2010.py file. When I try to run the command in the python shell census2010['AK']['Anchorage'] I get an error as follows:

Traceback (most recent call last):

File "<input>", line 1, in <module>

TypeError: 'module' object is not subscriptable

I am saving my files within a virtual enviroment using Pycharm if this makes any difference

Any help would be much appreciated

[EDIT] It's ok it works now...not sure what went wrong originally


r/inventwithpython • • Jun 07 '18

TIC TAC TOE 4TH EDITION CODE?

3 Upvotes

Can you share it? I've lost it and I would get crazy if I had to write it again.


r/inventwithpython • • Feb 08 '18

chapter 1 wrong awswer.

3 Upvotes

in 4 exercise : 4. Here are some words and their encryptions. Which key was used for each word? a. ROSEBUD – LIMYVOX b. YAMAMOTO – PRDRDFKF c. ASTRONOMY – HZAYVUVTF

the key of c is 7 ,not 19.


r/inventwithpython • • Oct 14 '17

HELP! STUCK IN AN INFINITE LOOP!!!

3 Upvotes

Hi guys, I just made this script to parse images. I however noticed that it goes into an infinite loop. How do I get out of it? The parsing part works well, the rest doesn't. Edit: SOLVED IT! the while-loop at the start doomed my script.


r/inventwithpython • • Oct 13 '17

The browser only opens from cmd when i type the full script and 2nd arg, NOT SO MUCH when i run the Batch file [AUTOMATE]

3 Upvotes

Hi guys, still having abit of trouble as I learn parsing. It's alot of hit and miss for me. This file, for instance, will only run as desired when I do it from command mode, but not so much from run. So far, the other batch files I've created run silky smooth. This one doesn't. At first the trying to run it, made windows concatenate the 2nd argument to the script, I had to add a space between the % and * in the batch file for it to almost run without errors. Now I don't get errors, but the browser doesn't open either.


r/inventwithpython • • Sep 23 '17

Do I need to re-install Python 3.6?

3 Upvotes

I'm constantly having problems running even the most simple modules. When I can get one to work, it won't work all the time. I've done the first 4-5 lessons and I've only got two to work.

For example; the most basic, the variable; I type Rec = 3, but when I type this or other variables, I get "Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> Rec NameError: name 'Rec' is not defined"

Sometimes it works, but most of the time it doesn't.

When I run import random

random.randint(1, 20) all I get is this error message. RESTART: C:\Users\user\AppData\Local\Programs\Python\Python36-32\Random Number.py


r/inventwithpython • • Sep 07 '17

[Automate] Table Printer Response Help

3 Upvotes

While looking for help on the Chapter 6 Project Table Printer, I came across a Stackoverflow answer that was really good. The problem is that I have trouble understanding the last 2 lines in the code.

Here's the answer:

Here's an alternate method that perhaps you could apply to your own code. I first took tableData and sorted it out into a dictionary so it's easier to work with. After that I found the longest list in terms of characters. This allows us to know how far over the shorter lists should go. Finally, I printed out each lists adding spaces in front of the shorter ones based on the difference from the longest.

    # orginal data
tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

# empty dictonary for sorting the data
newTable = {0:[], 1:[], 2:[], 3:[]}

# iterate through each list in tableData
for li in tableData:
    for i in range(len(li)):
        # put each item of tableData into newTable by index
        newTable[i].append(li[i])

# determine the longest list by number of total characters
# for instance ['apples', 'Alice', 'dogs'] would be 15 characters
# we will start with longest being zero at the start
longest = 0
# iterate through newTable
# for example the first key:value will be 0:['apples', 'Alice', 'dogs']
# we only really care about the value (the list) in this case
for key, value in newTable.items():
    # determine the total characters in each list
    # so effectively len('applesAlicedogs') for the first list
    length = len(''.join(value))
    # if the length is the longest length so far,
    # make that equal longest
    if length > longest:
        longest = length

# we will loop through the newTable one last time
# printing spaces infront of each list equal to the difference
# between the length of the longest list and length of the current list
# this way it's all nice and tidy to the right
for key, value in newTable.items():
    print(' ' * (longest - len(''.join(value))) + ' '.join(value))

Wouldn't the last 2 lines print out ' ' * (-16)? I'm pretty sure Python follows PEMDAS, so i'm having trouble understanding this. It would be nice if someone could explain or break up what's happening below, because if I try running this through PythonTutor it just displays the answer.

Stackoverflow Answer


r/inventwithpython • • Aug 19 '17

Character count

3 Upvotes

I was looking at the character count in chapter 5, here's the code:

message = "It was a bright cold day etc"
count = {}

for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1

print(count)

It works, but how does python know what "character" is? The program doesn't define it, so is the meaning built in to python itself?


r/inventwithpython • • Jul 12 '17

Solutions to Star Pusher puzzles. This is a WIP and is the levels that I have solved so far.

Thumbnail
drive.google.com
3 Upvotes

r/inventwithpython • • Apr 16 '17

Query from Automate the boring stuff book

3 Upvotes

Hi - I'm just working through Al's book online (complete Python/programming novice!) and struggling to understand why the programme below works to be honest. Would anyone be able to explain line by line what is going on and why?

Huge thanks in advance! Sam

catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):') name = raw_input() if name == '': break catNames = catNames + [name] # list concatenation print('The cat names are:') for name in catNames: print(' ' + name)


r/inventwithpython • • Mar 04 '17

[Automate] Ch. 3 Practice Project - collatz()

3 Upvotes

Ok so I bought the Automate the Boring Stuff with Python book and I am reading it and on Page 77 it asks you to write a program: This is right from the site, found here: https://automatetheboringstuff.com/chapter3/

"Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.

Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)

Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.

Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1.

The output of this program could look something like this:

Enter number: 3 10 5 16 8 4 2 1"

I am obviously doing several things wrong - the problem is that I don't know what to ask because I keep confusing myself. Here's my code that, when I run it, runs the "RESTART:" error: http://pastebin.com/FvzZcbjV

This is my first programming language experience so go easy on me.


r/inventwithpython • • Jan 11 '17

Automate the Boring Stuff, Chapter 7, Strong Password Detection. Got it to work, how do I improve it?

3 Upvotes

Pastebin with Code

I successfully was able to solve the Chapter 7 strong password detection challenge, and successfully get a true or false value with any inputted password.

However, I'm trying to take things a step further and have strings printed when a password is deficient stating what the deficiency is, as well as requesting a new password be entered.

I was able to get the string "Your Password needs to be at least 8 characters long. Please Try again" to print if the inputted password was not long enough. I want the same type of thing to happen if the password doesn't have a digit, or doesn't have at least 1 each of lower/uppercase letter.

The other step I want to try and include is that, if the inputted password does NOT meet one of the criteria, that the program requests and new password and then checks if that new password meets the criteria.

I realize the code I posted isn't really particularly close to doing any of that, but I've found that breaking apart code that I have all the tools to write helps me understand how to use those tools.

Thanks for your help!


r/inventwithpython • • Oct 25 '16

[Automate] Chapter 16 Project - Auto Unsubscriber

3 Upvotes

I'm having a hard time with this project and was looking for any help. The prompt is: "Write a program that scans through your email account, finds all the unsubscribe links in all your emails, and automatically opens them in a browser. This program will have to log in to your email provider’s IMAP server and download all of your emails. You can use BeautifulSoup (covered in Chapter 11) to check for any instance where the word unsubscribe occurs within an HTML link tag."

My idea was to login into my imap server and get the html message content from one message and pass that to a beautiful soup object. I then can parse through and find the unsubscribe links/elements. However, there appears to be an issue finding the elements I need or any elements I look for. It only picked up <div>.

So here is my code:

imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=False)

imapObj.login('<email>', '<password>')

imapObj.select_folder('INBOX', readonly=True)

UIDs = imapObj.search(['ALL'])

rawMessages = imapObj.fetch([<UID>]), [b'BODY[]'])

message = pyzmail.PyzMessage.factory(rawMessages[<UID>][b'BODY[]'])

htmlObj = message.html_part.get_payload().decode(message.html_part.charset)

soup = bs4.BeautifulSoup(htmlObj)

EDIT: If anyone's curious, I was able to figure out using BeautifulSoup and passing emails downloaded with pyzmail. I then selected the element with soup.select and used example_list[x].get('href') to get the URL.


r/inventwithpython • • Sep 14 '16

Chapter 9 Project - Fill in the Gaps

3 Upvotes

I'm having some issues with this project. Basically, what I've done is create a regex to find a file like spam001.txt. Then I walk through the folder, picking up any hits with my regex. After that, I'm looping through that list of objects and trying to see if I can find the ones that have the '1' or '2'. It's not really working. I'm not sure where to go after the walk through the folder or how to find sequential numbering. Here's my code:

import os, re, pprint

regex = re.compile(r'\w*\d\d\d.txt')

for folderName, subfolders, filenames in os.walk('.'):

    print(filenames)
    mo = regex.findall(pprint.pformat(filenames))
    
    number = 1
    
    for i in mo:
            if str(number) in i:
                    print(number)
                    print(i)
            
            else:
                    
            number = number + 1
            print(number)

Any help or guidance is really appreciated because I am really stuck.


r/inventwithpython • • Jul 08 '16

Unable to find/access the exercises for chapter 13 and beyond in "Hacking Secret Ciphers with Python"

3 Upvotes

I am unable to access any of these exercises, and feel that I should stop at this point, the exercises have been really helpful cementing things as I progress through this excellent text.

Any help would be greatly appreciated. Thank you.


r/inventwithpython • • Jun 18 '16

Firefox 47 breaks Selenium

3 Upvotes

This took me a while to figure out when my selenium scripts stopped working

See: https://www.mozilla.org/en-US/firefox/47.0/releasenotes/

If you haven't upgraded to 47, disable automatic updates in your Firefox settings. I'd wait until version 48 for (hopefully) a fix.


r/inventwithpython • • Sep 11 '15

Counting Google Search Results

3 Upvotes

I was trying to apply the content of Ch. 11 of "Automate..." and I am facing a freaky issue... My task is to search Google for news on a topic in a certain date range and count the number of results.

my simple code is

payload = {'as_epq': 'James Clark', 'tbs':'cdr:1,cd_min:1/01/2015,cd_max:1/01/2015','tbm':'nws'}

r = requests.get("https://www.google.com/search", params=payload)

soup = bs4.BeautifulSoup(r.text)

elems = soup.select('#resultStats')
print(elems[0].getText())

And the result I get is

About 8,600 results

So apparently all works... apart from the fact that the result is wrong. If I open the URL in Firefox (I can obtain the complete URL with r.url)

https://www.google.com/search?tbm=nws&as_epq=James+Clark&tbs=cdr%3A1%2Ccd_min%3A1%2F01%2F2015%2Ccd_max%3A1%2F01%2F2015

I see that the results are actually only 2, and if I manually download the HTML file, open the page source and search for id="resultStats" I find that the number of results is indeed 2!

Can anybody help me to understand why searching for the same id tag in the saved HTML file and in the soup item lead to two different numerical results?


UPDATE It seems that the problem is the custom date range that does not get processed correctly by requests.get. If I use the same URL with selenium I get the correct answer

from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
content = driver.page_source
soup = bs4.BeautifulSoup(content)
elems = soup.select('#resultStats')
print(elems[0].getText())

And the answer is

2 results (0.09 seconds) 

The problem is that this methodology seems to be more cumbersome because I need to open the page in Firefox...


r/inventwithpython • • Jul 07 '15

Comma Code, Ch.4 Not sure if I'm doing this right

3 Upvotes

This is a practice problem from Ch. 4 of the Automate book. I've attached my code here. I'm not sure how I can insert ', and' before the last word in any entered list value. I'm also not sure of the exact mechanics by which we approach how the list value is entered. For example, is it supposed to just be entered specifically as a sequence of words with commas between each word? I'd appreciate any help.

Comma Code

print('Please enter Newlist value') Newlist = [input()] Newlist.insert(-2, ', and ') print(Newlist)


r/inventwithpython • • Jul 02 '15

Chapter 13. Problems installing Docx

3 Upvotes

Hi Guys,

I'm working my way through chapter 13. I've installed PyPDF2, but can't install python-docx.

When I install it I get the error message as below.

building 'lxml.etree' extension
 C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown
  distribution option: 'bugtrack_url'
  warnings.warn(msg)
    error: Microsoft Visual C++ 10.0 is required (Unable to find    
vcvarsall.bat).


     ----------------------------------------
 Command "C:\Python34\python.exe -c "import setuptools,      
 tokenize;__file__='C:\\Users\\Ystan\\AppData\\Local\\Temp\\pip-       
build-j393xz49\\lxml\\setup.py';exec(compile(getattr(tokenize,  
'open', open)(__file__).read().replace('\r\n', '\n'), __file__,   
'exec'))" 
install --record C:\Users\Ystan\AppData\Local\Temp\pip-  
wctjdi_k-record\install-record.txt --single-version-externally- 
managed -- compile" failed with error code 1 in 
C:\Users\Ystan\AppData\Local\Temp\pip-build-j393xz49\lxml

I'm a real newbie who's only previous experience was Al's 2 other python books and am having trouble trying to google an answer.

I did try installing microsoft network framework 4 and visual studio (but that took a ton of hard drive space!) and it didn't seem to help.

Please help!

Thanks

YS


r/inventwithpython • • Jun 13 '15

image window disappears

3 Upvotes

The following code creates a window on my screen, which disappears after about 1 second:

---code--

import pygame, sys

from pygame.locals import *

'''set up pygame'''

pygame.init()

'''set up the window'''

windowSurface = pygame.display.set_mode((500, 400), 0, 32)

pygame.display.set_caption('Hello world!')

--end code--

I've tried it with two setups with the same result: python2.7 and python3.4.

Before I put 3.4 on my system, python2.7, it ran with what I expect is the correct behavior, i.e., the image persisted until I killed python. After installing 3.4 and pygame for 3.4, the current problem emerged.

My OS is Debian Wheezy.

ALSO, is it possible to post to this forum using email?

FINALLY, i looked at the formatting help page and i can't find a way to set code blocks in the messages.

thanks in advance ;o)