r/inventwithpython • • Oct 06 '18

Error in wikipedia subcategory crawling using python3

2 Upvotes

Hello Community Members,

I am getting the error `FileNotFoundError: [Errno 2] No such file or directory: 'categories/Category/Cricket.html' `. The code is as follows. Please help. Any sort of help is appreciated. I have been strucked onto this since last 3 days. The code is all about to extract all the subcategories name of wikipedia category in Python 3.

I have tried both the relative and absolute paths.

The code is as follows:

import httplib2 
from bs4 import BeautifulSoup 
import subprocess 
import time, wget 
import os, os.path  
#declarations 
catRoot = "http://en.wikipedia.org/wiki/Category:" 
MAX_DEPTH = 100 
done = [] 
ignore = [] 
path = 'trivial' 
#Removes all newline characters and replaces with spaces 
def removeNewLines(in_text): 
    return in_text.replace('\n', ' ') 
# Downloads a link into the destination 
def download(link, dest): 
# print link 
    if not os.path.exists(dest) or os.path.getsize(dest) == 0:     
        subprocess.getoutput('wget "' + link + '" -O "' + dest+ '"') 
        print ("Downloading") 

def ensureDir(f): 
    if not os.path.exists(f):         
        os.mkdir(f) 
# Cleans a text by removing tags 
def clean(in_text):  
    s_list = list(in_text)
        i,j = 0,0
        while i < len(s_list):
    #iterate until a left-angle bracket is found
            if s_list[i] == '<':
                if s_list[i+1] == 'b' and s_list[i+2] == 'r' and s_list[i+3] == '>':
                    i=i+1
                    print ("hello")
                    continue               
                while s_list[i] != '>':
    #pop everything from the the left-angle bracket until the right-angle bracket
                    s_list.pop(i)
    #pops the right-angle bracket, too
                s_list.pop(i)

            elif s_list[i] == '\n':
                s_list.pop(i)
            else:
                i=i+1        
    #convert the list back into text
    join_char=''
    return (join_char.join(s_list))#.replace("<br>","\n")

    def getBullets(content):
        mainSoup = BeautifulSoup(contents, "html.parser")
    
    # Gets empty bullets
    def getAllBullets(content):
        mainSoup = BeautifulSoup(str(content), "html.parser")
        subcategories = mainSoup.findAll('div',attrs={"class" : "CategoryTreeItem"})
        empty = []
        full = []
        for x in subcategories:
            subSoup = BeautifulSoup(str(x))
            link = str(subSoup.findAll('a')[0])
            if (str(x)).count("CategoryTreeEmptyBullet") > 0:
                empty.append(clean(link).replace(" ","_"))
            elif (str(x)).count("CategoryTreeBullet") > 0:
                full.append(clean(link).replace(" ","_"))

        return((empty,full))

    def printTree(catName, count):
        catName = catName.replace("\\'","'")
        if count == MAX_DEPTH : return
        download(catRoot+catName, path)
        filepath = "categories/Category:"+catName+".html" 

        print(filepath) 
        content = open('filepath', 'w+')

        content.readlines()
        (emptyBullets,fullBullets) = getAllBullets(content)
        f.close()
        for x in emptyBullets:
            for i in range(count): 
              print ("  "),
        download(catRoot+x, "categories/Category:"+x+".html")
        print (x)
        for x in fullBullets:
          for i in range(count): 
              print ("  "),
          print (x)
       	  if x in done:
       		 print ("Done... "+x)
       		 continue
          done.append(x)
          try: printTree(x, count + 1)        
          except: 
              print ("ERROR: " + x)
    name = "Cricket"
    printTree(name, 0)   

r/inventwithpython • • Jul 09 '18

Python code embedded in HTML

2 Upvotes

Hello, I am a python novice. Had a question regarding embedding python to format numbers to add commas within html. I am currently trying the below. I am not sure if I am using the right code or where/how to embed the code into my html code. Any help is greatly appreciated thank you!

df['column_name'] = df['column_name'].astype(int).apply(lambda x: "{:,}".format(x))


r/inventwithpython • • Jul 06 '18

how to output to input reverse python

2 Upvotes

input = "2"

p = input*2

print(p)

how do i take this out like exm:4 to next input and output wil be 8 this is example code


r/inventwithpython • • Mar 16 '18

Missing module

2 Upvotes

I tried to run this program that I download from your site.

Simple Substitution Dictionary Hacker, https://inventwithpython.com/hacking (BSD Licensed)

import pyperclip, simpleSubKeyword, detectEnglish

It fails with the message:

RESTART: D:\Users\patjd\My Software Projects\Python\Tutorial\simpleSubDictionaryHacker.py Traceback (most recent call last): File "D:\Users\patjd\My Software Projects\Python\Tutorial\simpleSubDictionaryHacker.py", line 2, in <module> import pyperclip, simpleSubKeyword, detectEnglish ModuleNotFoundError: No module named 'simpleSubKeyword'

I bought the Kindle edition of your book from Amazon.


r/inventwithpython • • Mar 05 '18

Created a new sheet with values not formulas in a bunch of spreadsheets.

2 Upvotes

I want use openpyxl to evaluate years of estimate spreadsheets. The spreadsheets use lots of formulas. One thought I could create new sheets say sheetname_values in each spreadsheet and then go manually cut and paste special by value to the new sheet. Any thoughts on how to automate the task?


r/inventwithpython • • Mar 05 '18

Error in Cracking Codes with Python

2 Upvotes

on page 236-7 the text has you testing the simpleSubHacker.addLettersToMapping function in the interactive shell. It has lines like: letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0]) in three places The addLettersToMapping function modifies the directory and doesn't return anything (see page 227), so the letterMapping1 = part of the line causes letterMapping1 to be set to None. When addLettersToMapping is called in the main program (page 229 line126) it is called without the assignment, ie simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0])


r/inventwithpython • • Feb 23 '18

Sonar.py question, function will never return false?

2 Upvotes

Hi there,

I'm confused about a particular bit of code in the 'Invent Your Own Computer Games' book. Chapter 13 (Sonar game), the text makes reference to the function makeMove returning False if the player makes an invalid move. As near as I can tell though, the function would never return False. Am I missing something? I've included the code below and at this pastebin: https://pastebin.com/ChmKEvdk

def makeMove(board, chests, x, y):
    # Change the board data structure with a sonar device character. Remove treasure chests from the chests list as they are found.
    # Return False if this is an invalid move.
    # Otherwise, return the string of the result of this move.
    smallestDistance = 100 # Any chest will be closer than 100.
    for cx, cy in chests: # For 'value 1' and 'value 2' in each index of the list
        # If each index didn't have two values, this wouldn't work.
        # This isn't a nested loop or anything.
        distance = math.sqrt((cx - x) * (cx - x) + (cy - y) * (cy - y))

        if distance < smallestDistance: # We want the closest treasure chest.
            smallestDistance = distance

    smallestDistance = round(smallestDistance)

    if smallestDistance == 0:
        # xy is directly on a treasure chest!
        chests.remove([x,y])
        return 'You have found a sunken treasure chest!'
    else:
        if smallestDistance < 10:
            board[x][y] = str(smallestDistance)
            return 'Treasure detected at a distance of %s from the sonar device' % (smallestDistance)
        else:
            board[x][y] = 'X'
            return 'Sonar did not detect anything. All treasure chests out of range.'

r/inventwithpython • • Feb 20 '18

We're working on a Spanish translation of the book! Come and help us!

Thumbnail
github.com
2 Upvotes

r/inventwithpython • • Feb 13 '18

Perfect - Thanks for explanation

2 Upvotes

r/inventwithpython • • Feb 12 '18

Question from Cracking Codes with Python, Chapter 24 'Programming the Public Key Cipher'

2 Upvotes

Hope I didn't inadvertently mis-title the orginal post as 'Hacking Secret Ciphers with Python'....I didn't have the book in front of me while posting.

Repeating original question here Hello Mr. Sweigart,

Just finished the book - I've never seen the math behind public key encryption, so really appreciated the clear and detailed walkthrough

Had a question regarding the 'Converting a block to a String' section. In this section, you state that in order to retrieve the original message text, the length of the original message must be known.

Is there another way to recover the original message text ? It seemed a odd that the length of the original text must be exposed to the person decrypting the message. Granted, you stated in the beginning of the chapter that this approach was only based on the RSA cipher, and there may be a part of the process you didn't talk about in your book - but if the original message length is something that has to be communicated to the person decrypting the message, how is this usually accomplished ? is it sent along with the encrypted message ?

Appreciate any additional insight you can provide on this part of the process.


r/inventwithpython • • Feb 12 '18

i need help with my python

2 Upvotes

import random import time

def displayIntro(): print('''You are in land full of dragons. In frount of you, you see two caves. In one cave, the dragon is frendly and will share his treaseure with you. The other dragon is greedy and hungry, and will eat you on sight.''')

print()

def chooseCave(): cave = '' while cave != '1' and cave != '2': print('which cave will you go into? (1 or 2)') cave = input()

return cave

def checkCave(chosenCave): print('you approach the cave...') time.sleep(2) print('its dark and spooky...') time.sleep(2) print('A large dragon jumps out in frount of you! He opens his jaws and...') print() time.sleep(2)

frendlyCave = random.randint(1,2)

if chosenCave == str(friendlyCave):
    print('throws up all his treasure all over you!')
else:
    print('Gobbles you down in one bite!')

playAgain = 'yes' while playAgain =='yes' or playAgain == 'y': displayIntro() caveNumber = chosenCave() checkCave(caveNumber)

print('do you want to play again? (yes/no)')
playAgain = input()

what it says about the problem

====== RESTART: /Users/Bella/Documents/python programing/dragon game.py ====== You are in land full of dragons. In frount of you, you see two caves. In one cave, the dragon is frendly and will share his treaseure with you. The other dragon is greedy and hungry, and will eat you on sight.

Traceback (most recent call last): File "/Users/Bella/Documents/python programing/dragon game.py", line 38, in <module> caveNumber = chosenCave() NameError: name 'chosenCave' is not defined


r/inventwithpython • • Jan 02 '18

Automate Boring Stuff: Ch. 10 Practice Proj

2 Upvotes

What bugs did you identify and fix?
I'm wanting to double check my solution to the Ch. 10 Practice Project: Debugging Coin Toss
Here's what I came up with: https://pastebin.com/X5wvWGSL


r/inventwithpython • • Dec 31 '17

pylint can't recognize pygame?

2 Upvotes

I found it's hard to find mistakes in my program, so I install pylint to find errors. But it show me this:


E: 5, 0: Module 'pygame' has no 'init' member (no-member)

E: 13,25: Module 'pygame' has no 'QUIT' member (no-member)

E: 14,12: Module 'pygame' has no 'quit' member (no-member)


These are not errors at all!Please give some suggestions, any help will be appreciated!


r/inventwithpython • • Jul 23 '17

Automate the boring stuff Table Printer

2 Upvotes

Hey this was the first thing in the book that was actaully quite challenging, this is my code. Probs really hard to read, but it works quite well no matter how long the text is. Also do we have to make it handle more than 3 lists and more than 3 list items, or do we just have to make it work with the example.

CODE

data

tableData = [['Alicegaetgeag','Bffffffffffob','Carffffffffffffffffffffffffffffol', 'David'],['affffffffffffffffpples', 'orangfeaaaaaaaaaaaaaes', 'cherries', 'bannanas'],['Dogs', 'Catf eaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas', 'Moose', 'Goose']]

setting col list which keeps track of colLength of eachlist

col = [0] *len(tableData) a = 0 length = 0 length1 = 0 length2 = 0

you want to iterate over each list item measuring the length of each if the, making sure to switch to new variable when you finish a list

for i in range(((len(tableData))*len(tableData[0]))): if i < 4: a = 0 if len(tableData[a][i]) > length: length = len(tableData[a][i]) col[0] = len(tableData[a][i])

if i > 3 and i < 8:
    a = 1
    i -= 4
    if len(tableData[a][i]) > length1:
        length1 = len(tableData[a][i])
        col[1] = len(tableData[a][i])
elif i > 7 :
    a = 2
    i -= 8
    if len(tableData[a][i]) > length2:
        length2 = len(tableData[a][i])
        col[2] = len(tableData[a][i])

if i+1%(len(tableData)+1) == 0:
    a += 1
    if a == 3:
        break

print(col) for i in range(len(tableData[0])): print(tableData[0][i].ljust(col[0]) + tableData[1][i].rjust(col[1]+1) + tableData[2][i].rjust((col[2])+1))


r/inventwithpython • • Jul 02 '17

Automate the Boring Stuff - Chapter 7 - Password Detection Problem help

2 Upvotes

Hi all; I'm attempting the problem I've listed in the title (link here: https://gyazo.com/984db9a628c9670a0181a0c22209fcfe).

Here is my script (https://gyazo.com/b38fe7a832c98aa198850fb590d7fec4) but when I run it I don't seem to get an output, getting this screen (https://gyazo.com/074dc02ec3924d3458da5e84dbbcaf90).

Any help would be brilliant, thanks in advance!


r/inventwithpython • • Jun 06 '17

More practices to cement things? [Automate]

2 Upvotes

Hi All,

I've been working through Automate the Boring Stuff after picking up a humble bundle for it ages ago. I love the writing style and the way things are explained, but I feel starved for practice opportunities to really drill loops into my head - I'm on Chapter 5 and for the last couple of chapters, I feel like I understand the concepts easily enough, I can answer the questions quickly and correctly, but then I stutter when I come to write it.

So I guess this post is both a comment for Al (I see you're kind enough to read this sub frequently), as well as a request for a recommendation for somewhere that just drills you on the stuff I've learnt in the last five chapters, so I can get them further ingrained in my head. Otherwise I worry that I'm building shaky foundations.

Thanks all!


r/inventwithpython • • May 07 '17

Hack for the Sea 2017 :: Come to Gloucester, MA and participate in our maritime hackathon!

Thumbnail
hackforthesea.com
2 Upvotes

r/inventwithpython • • Apr 22 '17

Chapter 6: Password Locker - Executing Script

2 Upvotes

I am having issues understanding how to run the script from Windows 10. I believe I correctly added the path to the environment variables. I created a batch file for this program. When I go to type pw email into the WIN-R window, it just comes back saying that Windows cannot find pw.

At this point I just am lost in this whole process. Can someone give me a step-by-step instruction on how to run a python script from Windows 10?


r/inventwithpython • • Apr 20 '17

Unsubscriber - pyzmail msg.html_part.charset vs. utf-8

2 Upvotes

I am working on the email unsubscriber program that uses imap, pyzmail, and beautifulsoup. I ran a couple tests and it seemed to be working fine. However, on another test (in which I didn’t change anything), I got an error message:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 21188: ordinal not in range(128)

This is the specific line it was failing on:

html=message.html_part.get_payload().decode(msg.html_part.charset)

From the best of my understanding, one of the emails it was trying to parse had a non-ASCII character that it was trying to convert to an ASCII character and failing to do. I saw a few workarounds that said to add this to the code:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

However, I am using python 3.5.2 and this solution seems to only work for python 2.7.

I looked into the pyzmail docs and swapped out a bit of the line that was failing so that it now looks like this:

html=message.html_part.get_payload().decode ('utf-8')

I ran another test and it seemed to work. However, I’m concerned that some of the html data is either being lost or altered. After getting the html, I am parsing it with regex to find words in the a tag like unsubscribe, optout, etc, and then getting the href in said tag. Am I just being paranoid, or do I need to be concerned about this conversion?


r/inventwithpython • • Apr 18 '17

Transposition Hacker not working

2 Upvotes

Hello,

I have this as my code for the Transposition Hacker, which is not working...

import detectEnglish, trans_decrypter

def main():

    myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu  plri ch nitaalr eiuengiteehb(e1  hilincegeoamn fubehgtarndcstudmd nM eu
eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad   l t oisn sit u1rnd stara nvhn fsedbh ee,n  e necrg6  8nmisv l nc muiftegiitm tutmg cm
shSs9fcie ebintcaets h  aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal
lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap
yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po  droB wtinue r Pieno nc ayieeto'lulcih sfnc  ownaSserbereiaSm-eaiah, nnrttgcC  maciiritvledastinideI
nn rms iehn tsigaBmuoetcetias rn"""

    hackedMessage = hackTransposition(myMessage)

    if hackedMessage == None:
        print("Failed to hack encryption")

    else:
        print("Copying hacked message to clipboard")
        print(hackedMessage)


def hackTransposition(message):
    print("Hacking...")

    print('(press CTRL+D or CTRL+C to quit at any time)')

    for key in range(1, len(message)):
        print("Trying key #%s..." % (key))
        decryptedText = trans_decrypter.decryptMessage(key, message)
        if key == 10:
            print(decryptedText)
        if detectEnglish.isEnglish(decryptedText):
            print()
            print("Possible encryption hack...")
            print("Key %s: %s" % (key,decryptedText[:100]))
            print("Enter D for done or just press ENTER to continue hacking:")
            response = input(">")

            if response.strip().upper().startswith("D"):
                return decryptedText

    return None
if __name__ == '__main__':
    main()

The decrypter for key 10 is producing this text, despite it working during the actual Transposition Decryption chapter:

myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1 hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit u1rnd stara nvhn fsedbh ee,n e necrg6 8nmisv l nc muiftegiitm tutmg cm shSs9fcie ebintcaets h aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po droB wtinue r Pieno nc ayieeto'lulcih sfnc ownaSserbereiaSm-eaiah, nnrttgcC maciiritvledastinideI nn rms iehn tsigaBmuoetcetias rn"""

Thus, there is no distinguishable English word, despite seeing remnants of bits and pieces of English, which tells me that the reason the Transposition hacker is failing has to do with the decryption process text or key being off. I tried the text as both a multi-line and single-line string.

I copied and pasted the text word-for-word multiple times from This page .

I'm stuck. Anyone else struggle with this? Thanks.


r/inventwithpython • • Mar 15 '17

[Invent] Collier Game

2 Upvotes

What is a easy way I can make a scoreboard for this game?


r/inventwithpython • • Mar 09 '17

Help with email programming smtplib

2 Upvotes

I follow the steps in the lecture but I get to this conn.login('[email protected]','Password!21!') and I get an error message

error Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> conn.login('####gmail.com','Password') File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login raise last_exception File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login initial_response_ok=initial_response_ok) File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu0\n5.7.14 NKFUCpcSofwu-eYFpQLPYk16p6IDG7Yw_80luBxOCC_XkPWETsZ-KAfIUytctZYmVcHXvl\n5.7.14 DIcC_EqwIriGUrHrhvW5mYR2Ot_jD_nmK-wKZFZGmsusdB1JDJJfqkK6T_kPOYVxQOmR-c\n5.7.14 Le-oApg21W60tYt_3e8FY-mhkLGY5lfnxgYH0UGac89tZTlmMNP9hInDTUCGhL3gd6ZtUW\n5.7.14 dvjzuGsV-EBXBMSDcCOjwAQ2MYNuA> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 32sm1689645uaw.14 - gsmtp')


r/inventwithpython • • Feb 24 '17

Chapter 9 Backup to Zip typos?

2 Upvotes

I'm going through Automate the Boring stuff and I'm following along with the Backup to Zip project. When I get to the third part about walking through the directory tree and adding the files and folders to the zip file I get this error:

NameError: name 'newBase' is not defined

for the for loop:

for filename in filenames:
    newBase / os.path.basename(folder) + '_'
    if filename.startswith(newBase) and filename.endswith('.zip')
        continue
    backupZip.write(os.path.join(foldername, filename))

At the end of the if statement I went ahead and added in a colon because it needs it, but I can't figure out how to get it to use newBase. I'm using Python 3 on Fedora 25.

Full code


r/inventwithpython • • Feb 20 '17

[AUTOMATE] Ch. 4 Lists - Comma Code Exercise

2 Upvotes

Hello World! first post ever to Reddit!

Just wanted to know how you guys found a solution to the Comma Code exercise in ch. 4 of automate the boring stuff.

I did a quick search for a solution but couldn't find one.

I know the exercise states to make a function but my solution was this...

name = input("Gimme a list value: ")

newName = name[0:-1] + " and " + name[-1]
print(newName)

Any (constructive) comments? I'll be mashing away trying to find a solution with a function in the mean time.


r/inventwithpython • • Jan 17 '17

newb pygame makers question

2 Upvotes

i'm trying to make movement in pygame. I want my charcter to move the whole time ,but i'm not sure how to do it. My friends said to keep loop the different sprites, but i'm not sure how to do it.