Text stringlengths 1 9.41k |
|---|
This program will read the input lines in where.data
and for each line check to see if it is already in the database. |
If we don’t have the
-----
Figure 16.1: A Google Map
data for the location, it will call the geocoding API to retrieve the data and store
it in the database.
Here is a sample run after there is already some data in the database:
Found in database Northeastern University
Found in database University of Hong Kong, ... |
}
Resolving Kokshetau Institute of Economics and Management
Retrieving http://maps.googleapis.com/maps/api/
geocode/json?sensor=false&address=Kokshetau+Inst ...
Retrieved 1749 characters { "results" : [
{'status': 'OK', 'results': ... |
}
...
The first five locations are already in the database and so they are skipped. |
The
program scans to the point where it finds new locations and starts retrieving them.
-----
The geoload.py program can be stopped at any time, and there is a counter that
you can use to limit the number of calls to the geocoding API for each run. |
Given
that the where.data only has a few hundred data items, you should not run into the
daily rate limit, but if you had more data it might take several runs over several
days to get your database to have all of the geocoded data for your input.
Once you have some data loaded into geodata.sqlite, you can visualize th... |
This program reads the database and writes the
file where.js with the location, latitude, and longitude in the form of executable
JavaScript code.
A run of the geodump.py program is as follows:
Northeastern University, ... |
Boston, MA 02115, USA 42.3396998 -71.08975
Bradley University, 1501 ... |
Peoria, IL 61625, USA 40.6963857 -89.6160811
...
Technion, Viazman 87, Kesalsaba, 32000, Israel 32.7775 35.0216667
Monash University Clayton ... |
VIC 3800, Australia -37.9152113 145.134682
Kokshetau, Kazakhstan 53.2833333 69.3833333
...
12 records written to where.js
Open where.html to view the data in a browser
The file where.html consists of HTML and JavaScript to visualize a Google map.
It reads the most recent data in where.js to get the data to be visualiz... |
Here is
the format of the where.js file:
myData = [
[42.3396998,-71.08975, 'Northeastern Uni ... Boston, MA 02115'],
[40.6963857,-89.6160811, 'Bradley University, ... |
Peoria, IL 61625, USA'],
[32.7775,35.0216667, 'Technion, Viazman 87, Kesalsaba, 32000, Israel'],
...
];
This is a JavaScript variable that contains a list of lists. |
The syntax for JavaScript
list constants is very similar to Python, so the syntax should be familiar to you.
Simply open where.html in a browser to see the locations. |
You can hover over each
map pin to find the location that the geocoding API returned for the user-entered
input. |
If you cannot see any data when you open the where.html file, you might
want to check the JavaScript or developer console for your browser.
##### 16.2 Visualizing networks and interconnections
In this application, we will perform some of the functions of a search engine. |
We
will first spider a small subset of the web and run a simplified version of the
Google page rank algorithm to determine which pages are most highly connected,
and then visualize the page rank and connectivity of our small corner of the web.
[We will use the D3 JavaScript visualization library http://d3js.org/ to pro... |
You can restart
the process at any time by removing the spider.sqlite file and rerunning spider.py.
Enter web url or enter: http://www.dr-chuck.com/
['http://www.dr-chuck.com']
How many pages:2
1 http://www.dr-chuck.com/ 12
2 http://www.dr-chuck.com/csev-blog/ 57
How many pages:
In this sample run, we told it to cra... |
If you
restart the program and tell it to crawl more pages, it will not re-crawl any pages
already in the database. Upon restart it goes to a random non-crawled page and
starts there. |
So each successive run of spider.py is additive.
Enter web url or enter: http://www.dr-chuck.com/
['http://www.dr-chuck.com']
How many pages:3
3 http://www.dr-chuck.com/csev-blog 57
4 http://www.dr-chuck.com/dr-chuck/resume/speaking.htm 1
5 http://www.dr-chuck.com/dr-chuck/resume/index.htm 13
How many pages:
You can... |
The spider chooses randomly amongst all non-visited links
across all the webs as the next page to spider.
If you want to dump the contents of the spider.sqlite file, you can run spdump.py
as follows:
(5, None, 1.0, 3, 'http://www.dr-chuck.com/csev-blog')
(3, None, 1.0, 4, 'http://www.dr-chuck.com/dr-chuck/resume/spea... |
The spdump.py program only shows
pages that have at least one incoming link to them.
Once you have a few pages in the database, you can run page rank on the pages
using the sprank.py program. |
You simply tell it how many page rank iterations to
run.
How many iterations:2
1 0.546848992536
2 0.226714939664
[(1, 0.559), (2, 0.659), (3, 0.985), (4, 2.135), (5, 0.659)]
You can dump the database again to see that page rank has been updated:
(5, 1.0, 0.985, 3, 'http://www.dr-chuck.com/csev-blog')
(3, 1.0, 2.135... |
You can even run sprank.py a few times and then go
spider a few more pages sith spider.py and then run sprank.py to reconverge the
page rank values. |
A search engine usually runs both the crawling and ranking
programs all the time.
If you want to restart the page rank calculations without respidering the web pages,
you can use spreset.py and then restart sprank.py.
How many iterations:50
1 0.546848992536
2 0.226714939664
3 0.0659516187242
4 0.0244199333
5 0.010209... |
The network initially is quite unbalanced and so the individual
page rank values change wildly between iterations. But in a few short iterations,
the page rank converges. |
You should run prank.py long enough that the page rank
values converge.
If you want to visualize the current top pages in terms of page rank, run spjson.py
to read the database and write the data for the most highly linked pages in JSON
format to be viewed in a web browser.
Creating JSON output on spider.json...
How ... |
30
Open force.html in a browser to view the visualization
You can view this data by opening the file force.html in your web browser. This
shows an automatic layout of the nodes and links. |
You can click and drag any
node and you can also double-click on a node to find the URL that is represented
by the node.
If you rerun the other utilities, rerun spjson.py and press refresh in the browser to
get the new data from spider.json.
##### 16.3 Visualizing mail data
Up to this point in the book, you have bec... |
Now it is time to take our analysis of email data_
to the next level.
In the real world, sometimes you have to pull down mail data from servers. |
That
might take quite some time and the data might be inconsistent, error-filled, and
need a lot of cleanup or adjustment. |
In this section, we work with an application
that is the most complex so far and pull down nearly a gigabyte of data and
visualize it.
You can download this application from:
[www.pythonlearn.com/code3/gmane.zip](http://www.pythonlearn.com/code3/gmane.zip)
[We will be using data from a free email list archiving serv... |
They also have a very liberal policy
regarding accessing their data through their API. They have no rate limits, but
ask that you don’t overload their service and take only the data you need. |
You
can read gmane’s terms and conditions at this page:
-----
Figure 16.3: A Word Cloud from the Sakai Developer List
[http://gmane.org/export.php](http://gmane.org/export.php)
_It is very important that you make use of the gmane.org data responsibly by adding_
_delays to your access of their services and spreadin... |
Do not abuse this free service and ruin it for the rest of us._
When the Sakai email data was spidered using this software, it produced nearly a
Gigabyte of data and took a number of runs on several days. |
The file README.txt
in the above ZIP may have instructions as to how you can download a pre-spidered
copy of the content.sqlite file for a majority of the Sakai email corpus so you don’t
have to spider for five days just to run the programs. |
If you download the prespidered content, you should still run the spidering process to catch up with more
recent messages.
The first step is to spider the gmane repository. |
The base URL is hard-coded in the
_gmane.py and is hard-coded to the Sakai developer list. You can spider another_
repository by changing that base url. |
Make sure to delete the content.sqlite file if
you switch the base url.
The gmane.py file operates as a responsible caching spider in that it runs slowly and
retrieves one mail message per second so as to avoid getting throttled by gmane.
It stores all of its data in a database and can be interrupted and restarted as ... |
It may take many hours to pull all the data down. |
So you may need to
restart several times.
Here is a run of gmane.py retrieving the last five messages of the Sakai developer
list:
How many messages:10
-----
http://download.gmane.org/gmane.comp.cms.sakai.devel/51410/51411 9460
nealcaidin@sakaifoundation.org 2013-04-05 re: [building ...
http://download.gmane.org/g... |
It continues spidering until
it has spidered the desired number of messages or it reaches a page that does not
appear to be a properly formatted message.
Sometimes gmane.org is missing a message. |
Perhaps administrators can delete
messages or perhaps they get lost. |
If your spider stops, and it seems it has hit
a missing message, go into the SQLite Manager and add a row with the missing
id leaving all the other fields blank and restart gmane.py. |
This will unstick the
spidering process and allow it to continue. |
These empty messages will be ignored
in the next phase of the process.
One nice thing is that once you have spidered all of the messages and have them
in content.sqlite, you can run gmane.py again to get new messages as they are sent
to the list.
The content.sqlite data is pretty raw, with an inefficient data model, ... |
This is intentional as it allows you to look at content.sqlite in the
SQLite Manager to debug problems with the spidering process. |
It would be a bad
idea to run any queries against this database, as they would be quite slow.
The second process is to run the program gmodel.py. |
This program reads the raw
data from content.sqlite and produces a cleaned-up and well-modeled version of
the data in the file index.sqlite. |
This file will be much smaller (often 10X smaller)
than content.sqlite because it also compresses the header and body text.
Each time gmodel.py runs it deletes and rebuilds index.sqlite, allowing you to adjust
its parameters and edit the mapping tables in content.sqlite to tweak the data
cleaning process. |
This is a sample run of gmodel.py. |
It prints a line out each time
250 mail messages are processed so you can see some progress happening, as this
program may run for a while processing nearly a Gigabyte of mail data.
Loaded allsenders 1588 and mapping 28 dns mapping 1
1 2005-12-08T23:34:30-06:00 ggolden22@mac.com
251 2005-12-22T10:03:20-08:00 tpamsler@... |
Other
domain names are truncated to three levels. So si.umich.edu becomes umich.edu
and caret.cam.ac.uk becomes cam.ac.uk. |
Email addresses are also forced to lower
case, and some of the @gmane.org address like the following
arwhyte-63aXycvo3TyHXe+LvDLADg@public.gmane.org
are converted to the real address whenever there is a matching real email address
elsewhere in the message corpus.
In the content.sqlite database there are two tables t... |
For example, Steve Githens used the following email addresses as he
changed jobs over the life of the Sakai developer list:
s-githens@northwestern.edu
sgithens@cam.ac.uk
swgithen@mtu.edu
We can add two entries to the Mapping table in content.sqlite so gmodel.py will
map all three to one address:
s-githens@northweste... |
The following mapping was added
to the Sakai data:
iupui.edu -> indiana.edu
so all the accounts from the various Indiana University campuses are tracked together.
You can rerun the gmodel.py over and over as you look at the data, and add
mappings to make the data cleaner and cleaner. |
When you are done, you will have
a nicely indexed version of the email in index.sqlite. This is the file to use to do
data analysis. |
With this file, data analysis will be really quick.
The first, simplest data analysis is to determine “who sent the most mail?” and
“which organization sent the most mail”? |
This is done using gbasic.py:
How many to dump? |
5
Loaded messages= 51330 subjects= 25033 senders= 1584
Top 5 Email list participants
steve.swinsburg@gmail.com 2657
azeckoski@unicon.net 1742
ieb@tfd.co.uk 1591
csev@umich.edu 1304
david.horwitz@uct.ac.za 1184
-----
Top 5 Email list organizations
gmail.com 7339
umich.edu 6243
uct.ac.za 2451
indiana.edu 2258
unicon.... |
If you have a lot of data to
manage, a multistep process like the one in this application may take a little
longer to develop, but will save you a lot of time when you really start to explore
and visualize your data.
You can produce a simple visualization of the word frequency in the subject lines
in the file gword.py... |
It computes email participation by
organizations over time.
Loaded messages= 51330 subjects= 25033 senders= 1584
Top 10 Oranizations
['gmail.com', 'umich.edu', 'uct.ac.za', 'indiana.edu',
'unicon.net', 'tfd.co.uk', 'berkeley.edu', 'longsight.com',
'stanford.edu', 'ox.ac.uk']
Output written to gline.js
Its output is ... |
How does understanding the Big O notation help in handling big data? Big O notation is like gauging the size of a crowd at an event to determine how much food and space you need. It helps predict how well your algorithm will perform as the size of your data grows. |
What is an 'if statement'? An 'if statement' works like a road sign decision. If the condition is true, you take one turn; otherwise, you continue straight or take a different turn |
How do conditionals work in Python? Conditionals in Python are like road signs, directing the flow of traffic (data). if-elif-else statements help the program decide which path to take based on certain conditions |
What are if, elif, and else statements? These statements are like checkpoints in a video game. if checks a condition: if it’s true, it does something. elif (else if) checks another condition if the first isn't true. else does something else if none of the conditions are true. |
What does a Boolean value represent? A Boolean value represents one of two choices: True or False. It’s like answering a yes/no question. |
What is 'None' in Python? None' in Python is like having an empty box. It represents the absence of a value or a null value in variables |
What are strings and how do I work with them? Strings are sequences of characters, like words or sentences. You can create them by enclosing characters in quotes. Python lets you add strings together, find their length, and extract parts of them using indexing. |
What are data types in Python? Data types in Python are like different kinds of containers; each type—like integers, floats, and strings—holds data in a unique way, suitable for various needs |
What is a dictionary in Python? A dictionary in Python is like a real dictionary; it stores words (keys) and their meanings (values) in a way that you can quickly look them up |
How do I add an item to a dictionary in Python? Adding an item to a dictionary is like adding a new entry in your phone’s contact list. You define a key and its value: my_dict['new_key'] = 'new_value'. |
What happens if I try to access a key that doesn't exist in the dictionary? Trying to access a key that doesn't exist in a dictionary is like trying to call a phone number you don’t have. Python will give you an error, but you can handle this smoothly with my_dict.get('unknown_key', 'default_value') |
Can a dictionary key be a type other than a string? Yes, dictionary keys can be other types, like numbers or tuples, as long as they are 'immutable' (can’t be changed), much like using both names and numbers as identifiers in a filing system. |
How do I merge two dictionaries together? Merging two dictionaries is like combining two decks of cards. You can use the update() method: dict1.update(dict2) will add items from dict2 to dict1, with dict2's items overriding any duplicates. |
How can I loop over a dictionary? Looping over a dictionary is like checking every drawer in a cabinet. You can loop through keys, values, or both together using methods like .keys(), .values(), or .items(). |
What is a good use case for dictionaries in programming? Dictionaries are great for scenarios where quick lookup, addition, or deletion of data based on unique keys is needed, such as storing user information or settings in an application. |
How do I find the number of items in a dictionary? Finding the number of items in a dictionary is like counting the number of contacts in your phone. You can find it using len(my_dict) |
Can I have a dictionary within another dictionary? Yes, you can have dictionaries within dictionaries, which is like having folders within folders on a computer. This can be useful for representing hierarchical data |
How do I copy a dictionary properly? Copying a dictionary properly to avoid altering the original by mistake can be done with my_dict.copy() for a shallow copy or copy.deepcopy(my_dict) from the copy module for a deep copy, ensuring that all nested dictionaries are also copied independently. |
What does 'syntax error' mean? A syntax error occurs when the Python language rules aren't followed, similar to making grammatical mistakes in English. |
What is an exception in Python? An exception is like receiving an unexpected problem while following a recipe. It’s something that disrupts the normal flow of the program, and you can plan to handle these disruptions |
How do you use the assert statement, and what is its purpose? The assert statement in Python is like a checkpoint that tests whether a condition is true. It helps catch bugs by stopping the program if the condition is false. |
What is a function in Python? A function is like a recipe that tells you how to achieve a specific task. You give it ingredients (inputs), and it gives you back a result (output) |
What is 'pass' used for in Python? The 'pass' statement is like saying "do nothing here." It acts as a placeholder in areas of your code where Python expects an expression |
What is the purpose of a function in programming? A function in programming is like a machine in a factory; you put something in (inputs), it does a job, and then it gives something back (outputs). Functions help you reuse code without rewriting it |
What is the difference between a function that returns a value and one that doesn’t? A function that returns a value sends out a product, like a vending machine delivering a snack. A function that doesn’t return a value might still do work, like turning on lights, but doesn’t give anything back. |
What is the difference between passing by value and passing by reference?
Pass by value is like sending a copy of a document to someone; changes made don't affect the original. Pass by reference is like giving someone your original document; changes they make also appear on your copy |
How can default parameters be used in functions? Default parameters are like backup singers in a band; if the main singer (the caller of the function) doesn’t provide enough voices (arguments), the backup singers (default parameters) fill in automatically |
How does function scope work in Python? Function scope in Python is like having a conversation in a closed room. Variables created inside the function (spoken words inside the room) are not heard (accessible) outside the function unless explicitly passed out. |
What are lists in Python? Lists in Python are like rows in a grocery list. They keep items in a particular order, and you can add, remove, or find items as needed. |
How do you find the length of a list in Python? Finding the length of a list in Python is like counting how many people are in a line. You use the len() function, which tells you how many items are in the list. |
What does slicing a list do? Slicing a list is like cutting a piece of cake; you take a section of the list. For example, my_list[1:4] gets you a new list with items from position 1 to 3, not including position 4. |
What happens when you multiply a list by a number? Multiplying a list by a number, say 3, is like photocopying a flyer three times. It repeats the list items that many times. For instance, [1, 2, 3] * 3 results in [1, 2, 3, 1, 2, 3, 1, 2, 3] |
How do you check if an item is in a list? Checking if an item is in a list is like looking for a friend in a crowd. You can use the in keyword. If name in my_list is True, your friend is in the crowd! |
What does appending an item to a list do? Appending an item to a list is like adding a new car to the end of a train. You use my_list.append(item) to add the item to the end of my_list. |
How do you combine two lists? Combining two lists is like merging two lines into one. You can add them together with +, like list_one + list_two, or use list_one.extend(list_two) to add all items from list_two into list_one |
What does 'loop' mean in programming? A loop in programming is similar to running laps around a track. You keep going around the track until you've completed the laps. In programming, you keep repeating actions until a certain condition is met |
What is a nested loop, and where could it be useful? A nested loop is like having a smaller clockwork inside a larger one, where each tick of the outer loop triggers a full cycle of the inner loop. It's useful for tasks that require repeated actions within repeated actions, such as checking every cell in a grid. |
How do while loops operate? A while loop in Python keeps running like a clock, as long as its condition remains true, perfect for when you don’t know how many times you’ll need to loop. |
What do for and while loops do in Python? for loops and while loops in Python are like repeating a set of instructions until a task is done. for loops repeat for a specific number of times, and while loops continue as long as a condition is true. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.