Tuesday, 13 September 2011

Example Scripts

Python Practice Scripts



"Unlucky!"

Working on simple user input scripts. The premise is when you enter what course you are studying, the script either replies in a positive manner 'Same as me!', or a negative "Unlucky!".

course = 'Digital Journalism'
JCourse = raw_input ('Please enter the course:')

if JCourse == 'Digital Journalism': 
    print 'Same as me.'
else:
    print 'Unlucky!'

Passwords

Here we tested requesting user inputs to match our ultra secure, top secret password (abc123). The raw_input represents the user's input. When the incorrect password is typed and RETURN is pressed, the script prints 'Incorrect'.
Below is the script.


secret_password = 'abc123'
password = raw_input('Please enter the password: ')

while password != secret_password:
    print 'Incorrect'
    password = raw_input('Please try again: ')


Email Verifier

This script simply verifies and prints email addresses. A real world application of this script could be to search through a data base or website or something similar for either a certain type of email eg. gmail or addresses ending in .ru . The script could then be adapted to print the results into a new text file on your Hard Drive/USB etc (see tweetfeed example).

import re

strings = ['My email address is leon@email.com',
          'This is not my email address']

email_pattern = '[\w._-]+@[\w._]+\.[A-Za-z]+'

for string in strings:
    match = re.search(email_pattern, string)
    if match == None:
        print 'No email address in: "', string, '"'
    else:
        print match.group(), 'is an email address'


Tweetfeed

This script was adapted to search for a certain word from Twitter. It does not, in its current form, support hashtags or users, but could be with a few additional lines of script. This example searches for "london" every 5 seconds and was adapted to print the results to text file.

import urllib2
import json
import time

tweets_data = urllib2.urlopen('http://search.twitter.com/search.json?q=london').read()
tweets = [tweet['text'] for tweet in json.loads(tweets_data)['results']]

while True:
    time.sleep(5)
	for tweet in tweets:
    	print tweet.encode('utf-8', 'ignore')

******************************

I'll try and edit this to add its printing functionality command soon. 

******************************


This page was written on Day5 in HTML mode to practice writing direct in HTML. The "< pre >" tag is used to seperate the normal text to the example code text.



Resources

Python Docs, w3 Schools

And here is my creativity for the week.

Caution: Coding in Progress

No comments:

Post a Comment