I'm from PPCG so I was making an esolang and I decided to write it in Python. Eventually it went from an esolang to an OEIS (Online Encyclopedia of Integer Sequences) lookup tool. I'm very new to Python.
Essentially this program takes an OEIS sequence number (e.g. 55
for sequence A000055
) and the nth number in the sequence to return.
The code gets the OEIS page, parses it with BeautifulSoup, and returns the result, if it doesn't exist it returns "OEIS does not have a number in the sequence at the given index".
import sys, re
from urllib2 import*
from bs4 import BeautifulSoup
# Main logic
def execute(code, nth):
# Decode input stuff
num = int(code)
try:
f = urlopen("http://oeis.org/A%06d/list" % num)
# global tree, data # Debugging
# >:D I'm sorry but I have to use RegEx to parse HTML
print {key: int(value) for key, value in
re.findall( r'(\d+) (\d+)', re.sub(r'\D+', " ", re.sub(r'<[^>]+>', "",
str(BeautifulSoup(f, "lxml").find(lambda tag:
tag.name == "table" and # A table
not tag.get('cellspacing') == "0" and # A table table
len(tag.contents) > 1 # A two column table
))
)) )
}.get(nth, "OEIS does not have a number in the sequence at the given index")
except HTTPError:
print "Could not find sequence A%06d" % num
except URLError:
print "Could not connect to sources";
except:
print "Verify your numbers are correct"
raise
if __name__ == '__main__':
if len(sys.argv) > 1:
execute(sys.argv[1], sys.argv[2])
else:
print """This is the OEIS lookup tool
You haven't entered the sequence""" % (LANGNAME)
As I'm new to Python. I'm using things I only kind of understand. My main concern is how I laid out this program. Especially the HTML parsing, I really doubt I'm doing that in the best way.
<center>
cannot hold... \$\endgroup\$