code
stringlengths
1
1.72M
language
stringclasses
1 value
from sys import stdin n = int(stdin.readline().strip()) print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
Python
from sys import stdin print len(stdin.readline().strip())
Python
from itertools import product from math import * def issqrt(n): s = int(floor(sqrt(n))) return s*s == n aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))] print ' '.join(map(str, filter(issqrt, aabb)))
Python
from sys import stdin a = map(int, stdin.readline().strip().split()) print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
Python
from sys import stdin def cycle(n): if n == 1: return 0 elif n % 2 == 1: return cycle(n*3+1) + 1 else: return cycle(n/2) + 1 n = int(stdin.readline().strip()) print cycle(n)
Python
from sys import stdin n = int(stdin.readline().strip()) count = n*2-1 for i in range(n): print ' '*i + '#'*count count -= 2
Python
for abc in range(123, 329): big = str(abc) + str(abc*2) + str(abc*3) if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
Python
from sys import stdin n, m = map(int, stdin.readline().strip().split()) print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
Python
from sys import stdin data = map(int, stdin.readline().strip().split()) n, m = data[0], data[-1] data = data[1:-1] print len(filter(lambda x: x < m, data))
Python
from sys import stdin def solve(a, b, c): for i in range(10, 101): if i % 3 == a and i % 5 == b and i % 7 == c: print i return print 'No answer' a, b, c = map(int, stdin.readline().strip().split()) solve(a, b, c)
Python
from itertools import product sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c] print '\n'.join(map(str, sol))
Python
from sys import stdin from math import * n = int(stdin.readline().strip()) print sum(map(factorial, range(1,n+1))) % (10**6)
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Alessandro Presta # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE ''' ====== tagger ====== Module for extracting tags from text documents. Copyright (C) 2011 by Alessandro Presta Configuration ============= Dependencies: python2.7, stemming, nltk (optional), lxml (optional), tkinter (optional) You can install the stemming package with:: $ easy_install stemming Usage ===== Tagging a text document from Python:: import tagger weights = pickle.load(open('data/dict.pkl', 'rb')) # or your own dictionary myreader = tagger.Reader() # or your own reader class mystemmer = tagger.Stemmer() # or your own stemmer class myrater = tagger.Rater(weights) # or your own... (you got the idea) mytagger = Tagger(myreader, mystemmer, myrater) best_3_tags = mytagger(text_string, 3) Running the module as a script:: $ ./tagger.py <text document(s) to tag> Example:: $ ./tagger.py tests/* Loading dictionary... Tags for tests/bbc1.txt : ['bin laden', 'obama', 'pakistan', 'killed', 'raid'] Tags for tests/bbc2.txt : ['jo yeates', 'bristol', 'vincent tabak', 'murder', 'strangled'] Tags for tests/bbc3.txt : ['snp', 'party', 'election', 'scottish', 'labour'] Tags for tests/guardian1.txt : ['bin laden', 'al-qaida', 'killed', 'pakistan', 'al-fawwaz'] Tags for tests/guardian2.txt : ['clegg', 'tory', 'lib dem', 'party', 'coalition'] Tags for tests/post1.txt : ['sony', 'stolen', 'playstation network', 'hacker attack', 'lawsuit'] Tags for tests/wikipedia1.txt : ['universe', 'anthropic principle', 'observed', 'cosmological', 'theory'] Tags for tests/wikipedia2.txt : ['beetroot', 'beet', 'betaine', 'blood pressure', 'dietary nitrate'] Tags for tests/wikipedia3.txt : ['the lounge lizards', 'jazz', 'john lurie', 'musical', 'albums'] ''' from __future__ import division import collections import re class Tag: ''' General class for tags (small units of text) ''' def __init__(self, string, stem=None, rating=1.0, proper=False, terminal=False): ''' @param string: the actual representation of the tag @param stem: the internal (usually stemmed) representation; tags with the same stem are regarded as equal @param rating: a measure of the tag's relevance in the interval [0,1] @param proper: whether the tag is a proper noun @param terminal: set to True if the tag is at the end of a phrase (or anyway it cannot be logically merged to the following one) @returns: a new L{Tag} object ''' self.string = string self.stem = stem or string self.rating = rating self.proper = proper self.terminal = terminal def __eq__(self, other): return self.stem == other.stem def __repr__(self): return repr(self.string) def __lt__(self, other): return self.rating > other.rating def __hash__(self): return hash(self.stem) class MultiTag(Tag): ''' Class for aggregates of tags (usually next to each other in the document) ''' def __init__(self, tail, head=None): ''' @param tail: the L{Tag} object to add to the first part (head) @param head: the (eventually absent) L{MultiTag} to be extended @returns: a new L{MultiTag} object ''' if not head: Tag.__init__(self, tail.string, tail.stem, tail.rating, tail.proper, tail.terminal) self.size = 1 self.subratings = [self.rating] else: self.string = ' '.join([head.string, tail.string]) self.stem = ' '.join([head.stem, tail.stem]) self.size = head.size + 1 self.proper = (head.proper and tail.proper) self.terminal = tail.terminal self.subratings = head.subratings + [tail.rating] self.rating = self.combined_rating() def combined_rating(self): ''' Method that computes the multitag's rating from the ratings of unit subtags (the default implementation uses the geometric mean - with a special treatment for proper nouns - but this method can be overridden) @returns: the rating of the multitag ''' # by default, the rating of a multitag is the geometric mean of its # unit subtags' ratings product = reduce(lambda x, y: x * y, self.subratings, 1.0) root = self.size # but proper nouns shouldn't be penalized by stopwords if product == 0.0 and self.proper: nonzero = [r for r in self.subratings if r > 0.0] if len(nonzero) == 0: return 0.0 product = reduce(lambda x, y: x * y, nonzero, 1.0) root = len(nonzero) return product ** (1.0 / root) class Reader: ''' Class for parsing a string of text to obtain tags (it just turns the string to lowercase and splits it according to whitespaces and punctuation, identifying proper nouns and terminal words; different rules and formats other than plain text could be used) ''' match_apostrophes = re.compile(r'`|’') match_paragraphs = re.compile(r'[\.\?!\t\n\r\f\v]+') match_phrases = re.compile(r'[,;:\(\)\[\]\{\}<>]+') match_words = re.compile(r'[\w\-\'_/&]+') def __call__(self, text): ''' @param text: the string of text to be tagged @returns: a list of tags respecting the order in the text ''' text = self.preprocess(text) # split by full stops, newlines, question marks... paragraphs = self.match_paragraphs.split(text) tags = [] for par in paragraphs: # split by commas, colons, parentheses... phrases = self.match_phrases.split(par) if len(phrases) > 0: # first phrase of a paragraph words = self.match_words.findall(phrases[0]) if len(words) > 1: tags.append(Tag(words[0].lower())) for w in words[1:-1]: tags.append(Tag(w.lower(), proper=w[0].isupper())) tags.append(Tag(words[-1].lower(), proper=words[-1][0].isupper(), terminal=True)) elif len(words) == 1: tags.append(Tag(words[0].lower(), terminal=True)) # following phrases for phr in phrases[1:]: words = self.match_words.findall(phr) if len(words) > 1: for w in words[:-1]: tags.append(Tag(w.lower(), proper=w[0].isupper())) if len(words) > 0: tags.append(Tag(words[-1].lower(), proper=words[-1][0].isupper(), terminal=True)) return tags def preprocess(self, text): ''' @param text: a string containing the text document to perform any required transformation before splitting @returns: the processed text ''' text = self.match_apostrophes.sub('\'', text) return text class Stemmer: ''' Class for extracting the stem of a word (by default it uses a simple open-source implementation of Porter's algorithm; this can be improved a lot, so experimenting with different ones is advisable; nltk.stem provides different algorithms for many languages) ''' match_contractions = re.compile(r'(\w+)\'(m|re|d|ve|s|ll|t)?') match_hyphens = re.compile(r'\b[\-_]\b') def __init__(self, stemmer=None): ''' @param stemmer: an object or module with a 'stem' method (defaults to stemming.porter2) @returns: a new L{Stemmer} object ''' if not stemmer: from stemming import porter2 stemmer = porter2 self.stemmer = stemmer def __call__(self, tag): ''' @param tag: the tag to be stemmed @returns: the stemmed tag ''' string = self.preprocess(tag.string) tag.stem = self.stemmer.stem(string) return tag def preprocess(self, string): ''' @param string: a string to be treated before passing it to the stemmer @returns: the processed string ''' # delete hyphens and underscores string = self.match_hyphens.sub('', string) # get rid of contractions and possessive forms match = self.match_contractions.match(string) if match: string = match.group(1) return string class Rater: ''' Class for estimating the relevance of tags (the default implementation uses TF (term frequency) multiplied by weight, but any other reasonable measure is fine; a quite rudimental heuristic tries to discard redundant tags) ''' def __init__(self, weights, multitag_size=3): ''' @param weights: a dictionary of weights normalized in the interval [0,1] @param multitag_size: maximum size of tags formed by multiple unit tags @returns: a new L{Rater} object ''' self.weights = weights self.multitag_size = multitag_size def __call__(self, tags): ''' @param tags: a list of (preferably stemmed) tags @returns: a list of unique (multi)tags sorted by relevance ''' self.rate_tags(tags) multitags = self.create_multitags(tags) # keep most frequent version of each tag clusters = collections.defaultdict(collections.Counter) proper = collections.defaultdict(int) ratings = collections.defaultdict(float) for t in multitags: clusters[t][t.string] += 1 if t.proper: proper[t] += 1 ratings[t] = max(ratings[t], t.rating) term_count = collections.Counter(multitags) for t, cnt in term_count.iteritems(): t.string = clusters[t].most_common(1)[0][0] proper_freq = proper[t] / cnt if proper_freq >= 0.5: t.proper = True t.rating = ratings[t] # purge duplicates, one-character tags and stopwords unique_tags = set(t for t in term_count if len(t.string) > 1 and t.rating > 0.0) # remove redundant tags for t, cnt in term_count.iteritems(): words = t.stem.split() for l in xrange(1, len(words)): for i in xrange(len(words) - l + 1): s = Tag(' '.join(words[i:i + l])) relative_freq = cnt / term_count[s] if ((relative_freq == 1.0 and t.proper) or (relative_freq >= 0.5 and t.rating > 0.0)): unique_tags.discard(s) else: unique_tags.discard(t) return sorted(unique_tags) def rate_tags(self, tags): ''' @param tags: a list of tags to be assigned a rating ''' term_count = collections.Counter(tags) for t in tags: # rating of a single tag is term frequency * weight t.rating = term_count[t] / len(tags) * self.weights.get(t.stem, 1.0) def create_multitags(self, tags): ''' @param tags: a list of tags (respecting the order in the text) @returns: a list of multitags ''' multitags = [] for i in xrange(len(tags)): t = MultiTag(tags[i]) multitags.append(t) for j in xrange(1, self.multitag_size): if t.terminal or i + j >= len(tags): break else: t = MultiTag(tags[i + j], t) multitags.append(t) return multitags class Tagger: ''' Master class for tagging text documents (this is a simple interface that should allow convenient experimentation by using different classes as building blocks) ''' def __init__(self, reader, stemmer, rater): ''' @param reader: a L{Reader} object @param stemmer: a L{Stemmer} object @param rater: a L{Rater} object @returns: a new L{Tagger} object ''' self.reader = reader self.stemmer = stemmer self.rater = rater def __call__(self, text, tags_number=5): ''' @param text: the string of text to be tagged @param tags_number: number of best tags to be returned Returns: a list of (hopefully) relevant tags ''' tags = self.reader(text) tags = map(self.stemmer, tags) tags = self.rater(tags) return tags[:tags_number] if __name__ == '__main__': import glob import pickle import sys if len(sys.argv) < 2: print 'No arguments given, running tests: ' documents = glob.glob('tests/*') else: documents = sys.argv[1:] print 'Loading dictionary... ' weights = pickle.load(open('data/dict.pkl', 'rb')) tagger = Tagger(Reader(), Stemmer(), Rater(weights)) for doc in documents: with open(doc, 'r') as file: print 'Tags for ', doc, ':' print tagger(file.read())
Python
#!/usr/bin/env python # Copyright (C) 2011 by Alessandro Presta # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE ''' Usage: build_dict.py -o <output file> -s <stopwords file> <list of files> ''' from __future__ import division from tagger import Stemmer from extras import SimpleReader def build_dict(corpus, stopwords=None, measure='IDF'): ''' @param corpus: a list of documents, represented as lists of (stemmed) words @param stopwords: the list of (stemmed) words that should have zero weight @param measure: the measure used to compute the weights ('IDF' i.e. 'inverse document frequency' or 'ICF' i.e. 'inverse collection frequency'; defaults to 'IDF') @returns: a dictionary of weights in the interval [0,1] ''' import collections import math dictionary = {} if measure == 'ICF': words = [w for doc in corpus for w in doc] term_count = collections.Counter(words) total_count = len(words) scale = math.log(total_count) for w, cnt in term_count.iteritems(): dictionary[w] = math.log(total_count / (cnt + 1)) / scale elif measure == 'IDF': corpus_size = len(corpus) scale = math.log(corpus_size) term_count = collections.defaultdict(int) for doc in corpus: words = set(doc) for w in words: term_count[w] += 1 for w, cnt in term_count.iteritems(): dictionary[w] = math.log(corpus_size / (cnt + 1)) / scale if stopwords: for w in stopwords: dictionary[w] = 0.0 return dictionary def build_dict_from_files(output_file, corpus_files, stopwords_file=None, reader=SimpleReader(), stemmer=Stemmer(), measure='IDF', verbose=False): ''' @param output_file: the name of the file where the dictionary should be saved @param corpus_files: a list of files with words to process @param stopwords_file: a file containing a list of stopwords @param reader: the L{Reader} object to be used @param stemmer: the L{Stemmer} object to be used @param measure: the measure used to compute the weights ('IDF' i.e. 'inverse document frequency' or 'ICF' i.e. 'inverse collection frequency'; defaults to 'IDF') @param verbose: whether information on the progress should be printed on screen ''' import pickle if verbose: print 'Processing corpus...' corpus = [] for filename in corpus_files: with open(filename, 'r') as doc: corpus.append(reader(doc.read())) corpus = [[w.stem for w in map(stemmer, doc)] for doc in corpus] stopwords = None if stopwords_file: if verbose: print 'Processing stopwords...' with open(stopwords_file, 'r') as sw: stopwords = reader(sw.read()) stopwords = [w.stem for w in map(stemmer, stopwords)] if verbose: print 'Building dictionary... ' dictionary = build_dict(corpus, stopwords, measure) with open(output_file, 'wb') as out: pickle.dump(dictionary, out, -1) if __name__ == '__main__': import getopt import sys try: options = getopt.getopt(sys.argv[1:], 'o:s:') output_file = options[0][0][1] stopwords_file = options[0][1][1] corpus = options[1] except: print __doc__ exit(1) build_dict_from_files(output_file, corpus, stopwords_file, verbose=True)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Alessandro Presta # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE ''' ====== tagger ====== Module for extracting tags from text documents. Copyright (C) 2011 by Alessandro Presta Configuration ============= Dependencies: python2.7, stemming, nltk (optional), lxml (optional), tkinter (optional) You can install the stemming package with:: $ easy_install stemming Usage ===== Tagging a text document from Python:: import tagger weights = pickle.load(open('data/dict.pkl', 'rb')) # or your own dictionary myreader = tagger.Reader() # or your own reader class mystemmer = tagger.Stemmer() # or your own stemmer class myrater = tagger.Rater(weights) # or your own... (you got the idea) mytagger = Tagger(myreader, mystemmer, myrater) best_3_tags = mytagger(text_string, 3) Running the module as a script:: $ ./tagger.py <text document(s) to tag> Example:: $ ./tagger.py tests/* Loading dictionary... Tags for tests/bbc1.txt : ['bin laden', 'obama', 'pakistan', 'killed', 'raid'] Tags for tests/bbc2.txt : ['jo yeates', 'bristol', 'vincent tabak', 'murder', 'strangled'] Tags for tests/bbc3.txt : ['snp', 'party', 'election', 'scottish', 'labour'] Tags for tests/guardian1.txt : ['bin laden', 'al-qaida', 'killed', 'pakistan', 'al-fawwaz'] Tags for tests/guardian2.txt : ['clegg', 'tory', 'lib dem', 'party', 'coalition'] Tags for tests/post1.txt : ['sony', 'stolen', 'playstation network', 'hacker attack', 'lawsuit'] Tags for tests/wikipedia1.txt : ['universe', 'anthropic principle', 'observed', 'cosmological', 'theory'] Tags for tests/wikipedia2.txt : ['beetroot', 'beet', 'betaine', 'blood pressure', 'dietary nitrate'] Tags for tests/wikipedia3.txt : ['the lounge lizards', 'jazz', 'john lurie', 'musical', 'albums'] ''' from __future__ import division import collections import re class Tag: ''' General class for tags (small units of text) ''' def __init__(self, string, stem=None, rating=1.0, proper=False, terminal=False): ''' @param string: the actual representation of the tag @param stem: the internal (usually stemmed) representation; tags with the same stem are regarded as equal @param rating: a measure of the tag's relevance in the interval [0,1] @param proper: whether the tag is a proper noun @param terminal: set to True if the tag is at the end of a phrase (or anyway it cannot be logically merged to the following one) @returns: a new L{Tag} object ''' self.string = string self.stem = stem or string self.rating = rating self.proper = proper self.terminal = terminal def __eq__(self, other): return self.stem == other.stem def __repr__(self): return repr(self.string) def __lt__(self, other): return self.rating > other.rating def __hash__(self): return hash(self.stem) class MultiTag(Tag): ''' Class for aggregates of tags (usually next to each other in the document) ''' def __init__(self, tail, head=None): ''' @param tail: the L{Tag} object to add to the first part (head) @param head: the (eventually absent) L{MultiTag} to be extended @returns: a new L{MultiTag} object ''' if not head: Tag.__init__(self, tail.string, tail.stem, tail.rating, tail.proper, tail.terminal) self.size = 1 self.subratings = [self.rating] else: self.string = ' '.join([head.string, tail.string]) self.stem = ' '.join([head.stem, tail.stem]) self.size = head.size + 1 self.proper = (head.proper and tail.proper) self.terminal = tail.terminal self.subratings = head.subratings + [tail.rating] self.rating = self.combined_rating() def combined_rating(self): ''' Method that computes the multitag's rating from the ratings of unit subtags (the default implementation uses the geometric mean - with a special treatment for proper nouns - but this method can be overridden) @returns: the rating of the multitag ''' # by default, the rating of a multitag is the geometric mean of its # unit subtags' ratings product = reduce(lambda x, y: x * y, self.subratings, 1.0) root = self.size # but proper nouns shouldn't be penalized by stopwords if product == 0.0 and self.proper: nonzero = [r for r in self.subratings if r > 0.0] if len(nonzero) == 0: return 0.0 product = reduce(lambda x, y: x * y, nonzero, 1.0) root = len(nonzero) return product ** (1.0 / root) class Reader: ''' Class for parsing a string of text to obtain tags (it just turns the string to lowercase and splits it according to whitespaces and punctuation, identifying proper nouns and terminal words; different rules and formats other than plain text could be used) ''' match_apostrophes = re.compile(r'`|’') match_paragraphs = re.compile(r'[\.\?!\t\n\r\f\v]+') match_phrases = re.compile(r'[,;:\(\)\[\]\{\}<>]+') match_words = re.compile(r'[\w\-\'_/&]+') def __call__(self, text): ''' @param text: the string of text to be tagged @returns: a list of tags respecting the order in the text ''' text = self.preprocess(text) # split by full stops, newlines, question marks... paragraphs = self.match_paragraphs.split(text) tags = [] for par in paragraphs: # split by commas, colons, parentheses... phrases = self.match_phrases.split(par) if len(phrases) > 0: # first phrase of a paragraph words = self.match_words.findall(phrases[0]) if len(words) > 1: tags.append(Tag(words[0].lower())) for w in words[1:-1]: tags.append(Tag(w.lower(), proper=w[0].isupper())) tags.append(Tag(words[-1].lower(), proper=words[-1][0].isupper(), terminal=True)) elif len(words) == 1: tags.append(Tag(words[0].lower(), terminal=True)) # following phrases for phr in phrases[1:]: words = self.match_words.findall(phr) if len(words) > 1: for w in words[:-1]: tags.append(Tag(w.lower(), proper=w[0].isupper())) if len(words) > 0: tags.append(Tag(words[-1].lower(), proper=words[-1][0].isupper(), terminal=True)) return tags def preprocess(self, text): ''' @param text: a string containing the text document to perform any required transformation before splitting @returns: the processed text ''' text = self.match_apostrophes.sub('\'', text) return text class Stemmer: ''' Class for extracting the stem of a word (by default it uses a simple open-source implementation of Porter's algorithm; this can be improved a lot, so experimenting with different ones is advisable; nltk.stem provides different algorithms for many languages) ''' match_contractions = re.compile(r'(\w+)\'(m|re|d|ve|s|ll|t)?') match_hyphens = re.compile(r'\b[\-_]\b') def __init__(self, stemmer=None): ''' @param stemmer: an object or module with a 'stem' method (defaults to stemming.porter2) @returns: a new L{Stemmer} object ''' if not stemmer: from stemming import porter2 stemmer = porter2 self.stemmer = stemmer def __call__(self, tag): ''' @param tag: the tag to be stemmed @returns: the stemmed tag ''' string = self.preprocess(tag.string) tag.stem = self.stemmer.stem(string) return tag def preprocess(self, string): ''' @param string: a string to be treated before passing it to the stemmer @returns: the processed string ''' # delete hyphens and underscores string = self.match_hyphens.sub('', string) # get rid of contractions and possessive forms match = self.match_contractions.match(string) if match: string = match.group(1) return string class Rater: ''' Class for estimating the relevance of tags (the default implementation uses TF (term frequency) multiplied by weight, but any other reasonable measure is fine; a quite rudimental heuristic tries to discard redundant tags) ''' def __init__(self, weights, multitag_size=3): ''' @param weights: a dictionary of weights normalized in the interval [0,1] @param multitag_size: maximum size of tags formed by multiple unit tags @returns: a new L{Rater} object ''' self.weights = weights self.multitag_size = multitag_size def __call__(self, tags): ''' @param tags: a list of (preferably stemmed) tags @returns: a list of unique (multi)tags sorted by relevance ''' self.rate_tags(tags) multitags = self.create_multitags(tags) # keep most frequent version of each tag clusters = collections.defaultdict(collections.Counter) proper = collections.defaultdict(int) ratings = collections.defaultdict(float) for t in multitags: clusters[t][t.string] += 1 if t.proper: proper[t] += 1 ratings[t] = max(ratings[t], t.rating) term_count = collections.Counter(multitags) for t, cnt in term_count.iteritems(): t.string = clusters[t].most_common(1)[0][0] proper_freq = proper[t] / cnt if proper_freq >= 0.5: t.proper = True t.rating = ratings[t] # purge duplicates, one-character tags and stopwords unique_tags = set(t for t in term_count if len(t.string) > 1 and t.rating > 0.0) # remove redundant tags for t, cnt in term_count.iteritems(): words = t.stem.split() for l in xrange(1, len(words)): for i in xrange(len(words) - l + 1): s = Tag(' '.join(words[i:i + l])) relative_freq = cnt / term_count[s] if ((relative_freq == 1.0 and t.proper) or (relative_freq >= 0.5 and t.rating > 0.0)): unique_tags.discard(s) else: unique_tags.discard(t) return sorted(unique_tags) def rate_tags(self, tags): ''' @param tags: a list of tags to be assigned a rating ''' term_count = collections.Counter(tags) for t in tags: # rating of a single tag is term frequency * weight t.rating = term_count[t] / len(tags) * self.weights.get(t.stem, 1.0) def create_multitags(self, tags): ''' @param tags: a list of tags (respecting the order in the text) @returns: a list of multitags ''' multitags = [] for i in xrange(len(tags)): t = MultiTag(tags[i]) multitags.append(t) for j in xrange(1, self.multitag_size): if t.terminal or i + j >= len(tags): break else: t = MultiTag(tags[i + j], t) multitags.append(t) return multitags class Tagger: ''' Master class for tagging text documents (this is a simple interface that should allow convenient experimentation by using different classes as building blocks) ''' def __init__(self, reader, stemmer, rater): ''' @param reader: a L{Reader} object @param stemmer: a L{Stemmer} object @param rater: a L{Rater} object @returns: a new L{Tagger} object ''' self.reader = reader self.stemmer = stemmer self.rater = rater def __call__(self, text, tags_number=5): ''' @param text: the string of text to be tagged @param tags_number: number of best tags to be returned Returns: a list of (hopefully) relevant tags ''' tags = self.reader(text) tags = map(self.stemmer, tags) tags = self.rater(tags) return tags[:tags_number] if __name__ == '__main__': import glob import pickle import sys if len(sys.argv) < 2: print 'No arguments given, running tests: ' documents = glob.glob('tests/*') else: documents = sys.argv[1:] print 'Loading dictionary... ' weights = pickle.load(open('data/dict.pkl', 'rb')) tagger = Tagger(Reader(), Stemmer(), Rater(weights)) for doc in documents: with open(doc, 'r') as file: print 'Tags for ', doc, ':' print tagger(file.read())
Python
# Copyright (C) 2011 by Alessandro Presta # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE from tagger import * class UnicodeReader(Reader): ''' Reader subclass that converts Unicode strings to a close ASCII representation ''' def __call__(self, text): import unicodedata text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') return Reader.__call__(self, text) class HTMLReader(UnicodeReader): ''' Reader subclass that can parse HTML code from the input ''' def __call__(self, html): import lxml.html text = lxml.html.fromstring(html).text_content() if isinstance(text, unicode): return UnicodeReader.__call__(self, text) else: return Reader.__call__(self, text) class SimpleReader(Reader): ''' Reader subclass that doesn't perform any advanced analysis of the text ''' def __call__(self, text): text = text.lower() text = self.preprocess(text) words = self.match_words.findall(text) tags = [Tag(w) for w in words] return tags class FastStemmer(Stemmer): ''' Stemmer subclass that uses a much faster, but less correct algorithm ''' def __init__(self): from stemming import porter Stemmer.__init__(self, porter) class NaiveRater(Rater): ''' Rater subclass that jusk ranks single-word tags by their frequency and weight ''' def __call__(self, tags): self.rate_tags(tags) # we still get rid of one-character tags and stopwords unique_tags = set(t for t in tags if len(t.string) > 1 and t.rating > 0.0) return sorted(unique_tags) def build_dict_from_nltk(output_file, corpus=None, stopwords=None, stemmer=Stemmer(), measure='IDF', verbose=False): ''' @param output_file: the name of the file where the dictionary should be saved @param corpus: the NLTK corpus to use (defaults to nltk.corpus.reuters) @param stopwords: a list of (not stemmed) stopwords (defaults to nltk.corpus.reuters.words('stopwords')) @param stemmer: the L{Stemmer} object to be used @param measure: the measure used to compute the weights ('IDF' i.e. 'inverse document frequency' or 'ICF' i.e. 'inverse collection frequency'; defaults to 'IDF') @param verbose: whether information on the progress should be printed on screen ''' from build_dict import build_dict import nltk import pickle if not (corpus and stopwords): nltk.download('reuters') corpus = corpus or nltk.corpus.reuters stopwords = stopwords or nltk.corpus.reuters.words('stopwords') corpus_list = [] if verbose: print 'Processing corpus...' for file in corpus.fileids(): doc = [stemmer(Tag(w.lower())).stem for w in corpus.words(file) if w[0].isalpha()] corpus_list.append(doc) if verbose: print 'Processing stopwords...' stopwords = [stemmer(Tag(w.lower())).stem for w in stopwords] if verbose: print 'Building dictionary... ' dictionary = build_dict(corpus_list, stopwords, measure) with open(output_file, 'wb') as out: pickle.dump(dictionary, out, -1)
Python
#!/usr/bin/env python # Copyright (C) 2011 by Alessandro Presta # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE ''' Usage: build_dict.py -o <output file> -s <stopwords file> <list of files> ''' from __future__ import division from tagger import Stemmer from extras import SimpleReader def build_dict(corpus, stopwords=None, measure='IDF'): ''' @param corpus: a list of documents, represented as lists of (stemmed) words @param stopwords: the list of (stemmed) words that should have zero weight @param measure: the measure used to compute the weights ('IDF' i.e. 'inverse document frequency' or 'ICF' i.e. 'inverse collection frequency'; defaults to 'IDF') @returns: a dictionary of weights in the interval [0,1] ''' import collections import math dictionary = {} if measure == 'ICF': words = [w for doc in corpus for w in doc] term_count = collections.Counter(words) total_count = len(words) scale = math.log(total_count) for w, cnt in term_count.iteritems(): dictionary[w] = math.log(total_count / (cnt + 1)) / scale elif measure == 'IDF': corpus_size = len(corpus) scale = math.log(corpus_size) term_count = collections.defaultdict(int) for doc in corpus: words = set(doc) for w in words: term_count[w] += 1 for w, cnt in term_count.iteritems(): dictionary[w] = math.log(corpus_size / (cnt + 1)) / scale if stopwords: for w in stopwords: dictionary[w] = 0.0 return dictionary def build_dict_from_files(output_file, corpus_files, stopwords_file=None, reader=SimpleReader(), stemmer=Stemmer(), measure='IDF', verbose=False): ''' @param output_file: the name of the file where the dictionary should be saved @param corpus_files: a list of files with words to process @param stopwords_file: a file containing a list of stopwords @param reader: the L{Reader} object to be used @param stemmer: the L{Stemmer} object to be used @param measure: the measure used to compute the weights ('IDF' i.e. 'inverse document frequency' or 'ICF' i.e. 'inverse collection frequency'; defaults to 'IDF') @param verbose: whether information on the progress should be printed on screen ''' import pickle if verbose: print 'Processing corpus...' corpus = [] for filename in corpus_files: with open(filename, 'r') as doc: corpus.append(reader(doc.read())) corpus = [[w.stem for w in map(stemmer, doc)] for doc in corpus] stopwords = None if stopwords_file: if verbose: print 'Processing stopwords...' with open(stopwords_file, 'r') as sw: stopwords = reader(sw.read()) stopwords = [w.stem for w in map(stemmer, stopwords)] if verbose: print 'Building dictionary... ' dictionary = build_dict(corpus, stopwords, measure) with open(output_file, 'wb') as out: pickle.dump(dictionary, out, -1) if __name__ == '__main__': import getopt import sys try: options = getopt.getopt(sys.argv[1:], 'o:s:') output_file = options[0][0][1] stopwords_file = options[0][1][1] corpus = options[1] except: print __doc__ exit(1) build_dict_from_files(output_file, corpus, stopwords_file, verbose=True)
Python
# -*- coding: utf8 -*- from fuzzywuzzy import fuzz from fuzzywuzzy import process from fuzzywuzzy import utils import itertools import unittest class UtilsTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.mixed_strings = [ "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", "C'est la vie", "Ça va?", "Cães danados", u"\xacCamarões assados", u"a\xac\u1234\u20ac\U00008000", u"\u00C1" ] def tearDown(self): pass def test_asciidammit(self): for s in self.mixed_strings: utils.asciidammit(s) def test_asciionly(self): for s in self.mixed_strings: # ascii only only runs on strings s = utils.asciidammit(s) utils.asciionly(s) def test_fullProcess(self): for s in self.mixed_strings: utils.full_process(s) class RatioTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.cirque_strings = [ "cirque du soleil - zarkana - las vegas", "cirque du soleil ", "cirque du soleil las vegas", "zarkana las vegas", "las vegas cirque du soleil at the bellagio", "zarakana - cirque du soleil - bellagio" ] self.baseball_strings = [ "new york mets vs chicago cubs", "chicago cubs vs chicago white sox", "philladelphia phillies vs atlanta braves", "braves vs mets", ] def tearDown(self): pass def testEqual(self): self.assertEqual(fuzz.ratio(self.s1, self.s1a),100) def testCaseInsensitive(self): self.assertNotEqual(fuzz.ratio(self.s1, self.s2),100) self.assertEqual(fuzz.ratio(utils.full_process(self.s1), utils.full_process(self.s2)),100) def testPartialRatio(self): self.assertEqual(fuzz.partial_ratio(self.s1, self.s3),100) def testTokenSortRatio(self): self.assertEqual(fuzz.token_sort_ratio(self.s1, self.s1a),100) def testPartialTokenSortRatio(self): self.assertEqual(fuzz.partial_token_sort_ratio(self.s1, self.s1a),100) self.assertEqual(fuzz.partial_token_sort_ratio(self.s4, self.s5),100) def testTokenSetRatio(self): self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5),100) def testPartialTokenSetRatio(self): self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5),100) def testQuickRatioEqual(self): self.assertEqual(fuzz.QRatio(self.s1, self.s1a), 100) def testQuickRatioCaseInsensitive(self): self.assertEqual(fuzz.QRatio(self.s1, self.s2), 100) def testQuickRatioNotEqual(self): self.assertNotEqual(fuzz.QRatio(self.s1, self.s3), 100) def testWRatioEqual(self): self.assertEqual(fuzz.WRatio(self.s1, self.s1a), 100) def testWRatioCaseInsensitive(self): self.assertEqual(fuzz.WRatio(self.s1, self.s2), 100) def testWRatioPartialMatch(self): # a partial match is scaled by .9 self.assertEqual(fuzz.WRatio(self.s1, self.s3), 90) def testWRatioMisorderedMatch(self): # misordered full matches are scaled by .95 self.assertEqual(fuzz.WRatio(self.s4, self.s5), 95) def testWRatioUnicode(self): self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100) def testQRatioUnicode(self): self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100) def testIssueSeven(self): s1 = "HSINCHUANG" s2 = "SINJHUAN" s3 = "LSINJHUANG DISTRIC" s4 = "SINJHUANG DISTRICT" self.assertTrue(fuzz.partial_ratio(s1, s2) > 75) self.assertTrue(fuzz.partial_ratio(s1, s3) > 75) self.assertTrue(fuzz.partial_ratio(s1, s4) > 75) def testWRatioUnicodeString(self): s1 = u"\u00C1" s2 = "ABCD" score = fuzz.WRatio(s1, s2) self.assertEqual(0, score) def testQRatioUnicodeString(self): s1 = u"\u00C1" s2 = "ABCD" score = fuzz.QRatio(s1, s2) self.assertEqual(0, score) # test processing methods def testGetBestChoice1(self): query = "new york mets at atlanta braves" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], "braves vs mets") def testGetBestChoice2(self): query = "philadelphia phillies at atlanta braves" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[2]) def testGetBestChoice3(self): query = "atlanta braves at philadelphia phillies" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[2]) def testGetBestChoice4(self): query = "chicago cubs vs new york mets" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[0]) class ProcessTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.cirque_strings = [ "cirque du soleil - zarkana - las vegas", "cirque du soleil ", "cirque du soleil las vegas", "zarkana las vegas", "las vegas cirque du soleil at the bellagio", "zarakana - cirque du soleil - bellagio" ] self.baseball_strings = [ "new york mets vs chicago cubs", "chicago cubs vs chicago white sox", "philladelphia phillies vs atlanta braves", "braves vs mets", ] def testWithProcessor(self): events = [ ["chicago cubs vs new york mets", "CitiField", "2011-05-11", "8pm"], ["new york yankees vs boston red sox", "Fenway Park", "2011-05-11", "8pm"], ["atlanta braves vs pittsburgh pirates", "PNC Park", "2011-05-11", "8pm"], ] query = "new york mets vs chicago cubs" processor = lambda event: event[0] best = process.extractOne(query, events, processor=processor) self.assertEqual(best[0], events[0]) def testWithScorer(self): choices = [ "new york mets vs chicago cubs", "chicago cubs at new york mets", "atlanta braves vs pittsbugh pirates", "new york yankees vs boston red sox" ] # in this hypothetical example we care about ordering, so we use quick ratio query = "new york mets at chicago cubs" scorer = fuzz.QRatio # first, as an example, the normal way would select the "more 'complete' match of choices[1]" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) # now, use the custom scorer best = process.extractOne(query, choices, scorer=scorer) self.assertEqual(best[0], choices[0]) def testWithCutoff(self): choices = [ "new york mets vs chicago cubs", "chicago cubs at new york mets", "atlanta braves vs pittsbugh pirates", "new york yankees vs boston red sox" ] query = "los angeles dodgers vs san francisco giants" # in this situation, this is an event that does not exist in the list # we don't want to randomly match to something, so we use a reasonable cutoff best = process.extractOne(query, choices, score_cutoff=50) self.assertTrue(best is None) #self.assertIsNone(best) # unittest.TestCase did not have assertIsNone until Python 2.7 # however if we had no cutoff, something would get returned #best = process.extractOne(query, choices) #self.assertIsNotNone(best) def testEmptyStrings(self): choices = [ "", "new york mets vs chicago cubs", "new york yankees vs boston red sox", "", "" ] query = "new york mets at chicago cubs" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) def testNullStrings(self): choices = [ None, "new york mets vs chicago cubs", "new york yankees vs boston red sox", None, None ] query = "new york mets at chicago cubs" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) if __name__ == '__main__': unittest.main() # run all tests
Python
import string bad_chars='' for i in range(128,256): bad_chars+=chr(i) table_from=string.punctuation+string.ascii_uppercase table_to=' '*len(string.punctuation)+string.ascii_lowercase trans_table=string.maketrans(table_from, table_to) def asciionly(s): return s.translate(None, bad_chars) # remove non-ASCII characters from strings def asciidammit(s): if type(s) is str: return asciionly(s) elif type(s) is unicode: return asciionly(s.encode('ascii', 'ignore')) else: return asciidammit(unicode(s)) def validate_string(s): try: if len(s)>0: return True else: return False except: return False def full_process(s): s = asciidammit(s) return s.translate(trans_table, bad_chars).strip() def intr(n): '''Returns a correctly rounded integer''' return int(round(n))
Python
#!/usr/bin/env python # encoding: utf-8 """ process.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from fuzz import * import sys, os import utils ####################################### # Find Best Matchs In List Of Choices # ####################################### def extract(query, choices, processor=None, scorer=None, limit=5): # choices = a list of objects we are attempting to extract values from # query = an object representing the thing we want to find # scorer f(OBJ, QUERY) --> INT. We will return the objects with the highest score # by default, we use score.WRatio() and both OBJ and QUERY should be strings # processor f(OBJ_A) --> OBJ_B, where the output is an input to scorer # for example, "processor = lambda x: x[0]" would return the first element in a collection x (of, say, strings) # this would then be used in the scoring collection if choices is None or len(choices) == 0: return [] # default, turn whatever the choice is into a string if processor is None: processor = lambda x: utils.asciidammit(x) # default: wratio if scorer is None: scorer = WRatio sl = list() for choice in choices: processed = processor(choice) score = scorer(query, processed) tuple = (choice, score) sl.append(tuple) sl.sort(key=lambda i: -1*i[1]) return sl[:limit] ########################## # Find Single Best Match # ########################## def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0): # convenience method which returns the single best choice # optional parameter: score_cutoff. # If the best choice has a score of less than score_cutoff # we will return none (intuition: not a good enough match) best_list = extract(query, choices, processor, scorer, limit=1) if len(best_list) > 0: best = best_list[0] if best[1] > score_cutoff: return best else: return None else: return None
Python
#!/usr/bin/env python # encoding: utf-8 """ score.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import os import re from utils import * try: from StringMatcher import StringMatcher as SequenceMatcher except: from difflib import SequenceMatcher REG_TOKEN = re.compile("[\w\d]+") ########################### # Basic Scoring Functions # ########################### def ratio(s1, s2): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") m = SequenceMatcher(None, s1, s2) return intr(100 * m.ratio()) # todo: skip duplicate indexes for a little more speed def partial_ratio(s1, s2): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") if len(s1) <= len(s2): shorter = s1; longer = s2; else: shorter = s2; longer = s1 m = SequenceMatcher(None, shorter, longer) blocks = m.get_matching_blocks() # each block represents a sequence of matching characters in a string # of the form (idx_1, idx_2, len) # the best partial match will block align with at least one of those blocks # e.g. shorter = "abcd", longer = XXXbcdeEEE # block = (1,3,3) # best score === ratio("abcd", "Xbcd") scores = [] for block in blocks: long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0 long_end = long_start + len(shorter) long_substr = longer[long_start:long_end] m2 = SequenceMatcher(None, shorter, long_substr) r = m2.ratio() if r > .995: return 100 else: scores.append(r) return int(100 * max(scores)) ############################## # Advanced Scoring Functions # ############################## # Sorted Token # find all alphanumeric tokens in the string # sort those tokens and take ratio of resulting joined strings # controls for unordered string elements def _token_sort(s1, s2, partial=True): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") # pull tokens tokens1 = REG_TOKEN.findall(s1) tokens2 = REG_TOKEN.findall(s2) # sort tokens and join sorted1 = u" ".join(sorted(tokens1)) sorted2 = u" ".join(sorted(tokens2)) sorted1 = sorted1.strip() sorted2 = sorted2.strip() if partial: return partial_ratio(sorted1, sorted2) else: return ratio(sorted1, sorted2) def token_sort_ratio(s1, s2): return _token_sort(s1, s2, False) def partial_token_sort_ratio(s1, s2): return _token_sort(s1, s2, True) # Token Set # find all alphanumeric tokens in each string...treat them as a set # construct two strings of the form # <sorted_intersection><sorted_remainder> # take ratios of those two strings # controls for unordered partial matches def _token_set(s1, s2, partial=True): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") # pull tokens tokens1 = set(REG_TOKEN.findall(s1)) tokens2 = set(REG_TOKEN.findall(s2)) intersection = tokens1.intersection(tokens2) diff1to2 = tokens1.difference(tokens2) diff2to1 = tokens2.difference(tokens1) sorted_sect = u" ".join(sorted(intersection)) sorted_1to2 = u" ".join(sorted(diff1to2)) sorted_2to1 = u" ".join(sorted(diff2to1)) combined_1to2 = sorted_sect + " " + sorted_1to2 combined_2to1 = sorted_sect + " " + sorted_2to1 # strip sorted_sect = sorted_sect.strip() combined_1to2 = combined_1to2.strip() combined_2to1 = combined_2to1.strip() pairwise = [ ratio(sorted_sect, combined_1to2), ratio(sorted_sect, combined_2to1), ratio(combined_1to2, combined_2to1) ] return max(pairwise) # if partial: # # partial_token_set_ratio # # else: # # token_set_ratio # tsr = ratio(combined_1to2, combined_2to1) # return tsr def token_set_ratio(s1, s2): return _token_set(s1, s2, False) def partial_token_set_ratio(s1, s2): return _token_set(s1, s2, True) # TODO: numerics ################### # Combination API # ################### # q is for quick def QRatio(s1, s2): if not validate_string(s1): return 0 if not validate_string(s2): return 0 p1 = full_process(s1) p2 = full_process(s2) return ratio(p1, p2) # w is for weighted def WRatio(s1, s2): p1 = full_process(s1) p2 = full_process(s2) if not validate_string(p1): return 0 if not validate_string(p2): return 0 # should we look at partials? try_partial = True unbase_scale = .95 partial_scale = .90 base = ratio(p1, p2) len_ratio = float(max(len(p1),len(p2)))/min(len(p1),len(p2)) # if strings are similar length, don't use partials if len_ratio < 1.5: try_partial = False # if one string is much much shorter than the other if len_ratio > 8: partial_scale = .6 if try_partial: partial = partial_ratio(p1, p2) * partial_scale ptsor = partial_token_sort_ratio(p1, p2) * unbase_scale * partial_scale ptser = partial_token_set_ratio(p1, p2) * unbase_scale * partial_scale return int(max(base, partial, ptsor, ptser)) else: tsor = token_sort_ratio(p1, p2) * unbase_scale tser = token_set_ratio(p1, p2) * unbase_scale return int(max(base, tsor, tser))
Python
#!/usr/bin/env python # encoding: utf-8 """ StringMatcher.py ported from python-Levenshtein [https://github.com/miohtama/python-Levenshtein] """ from Levenshtein import * from warnings import warn class StringMatcher: """A SequenceMatcher-like class built on the top of Levenshtein""" def _reset_cache(self): self._ratio = self._distance = None self._opcodes = self._editops = self._matching_blocks = None def __init__(self, isjunk=None, seq1='', seq2=''): if isjunk: warn("isjunk not NOT implemented, it will be ignored") self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seqs(self, seq1, seq2): self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seq1(self, seq1): self._str1 = seq1 self._reset_cache() def set_seq2(self, seq2): self._str2 = seq2 self._reset_cache() def get_opcodes(self): if not self._opcodes: if self._editops: self._opcodes = opcodes(self._editops, self._str1, self._str2) else: self._opcodes = opcodes(self._str1, self._str2) return self._opcodes def get_editops(self): if not self._editops: if self._opcodes: self._editops = editops(self._opcodes, self._str1, self._str2) else: self._editops = editops(self._str1, self._str2) return self._editops def get_matching_blocks(self): if not self._matching_blocks: self._matching_blocks = matching_blocks(self.get_opcodes(), self._str1, self._str2) return self._matching_blocks def ratio(self): if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def quick_ratio(self): # This is usually quick enough :o) if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def real_quick_ratio(self): len1, len2 = len(self._str1), len(self._str2) return 2.0 * min(len1, len2) / (len1 + len2) def distance(self): if not self._distance: self._distance = distance(self._str1, self._str2) return self._distance
Python
#!/usr/bin/env python # encoding: utf-8 """ process.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from fuzz import * import sys, os import utils ####################################### # Find Best Matchs In List Of Choices # ####################################### def extract(query, choices, processor=None, scorer=None, limit=5): # choices = a list of objects we are attempting to extract values from # query = an object representing the thing we want to find # scorer f(OBJ, QUERY) --> INT. We will return the objects with the highest score # by default, we use score.WRatio() and both OBJ and QUERY should be strings # processor f(OBJ_A) --> OBJ_B, where the output is an input to scorer # for example, "processor = lambda x: x[0]" would return the first element in a collection x (of, say, strings) # this would then be used in the scoring collection if choices is None or len(choices) == 0: return [] # default, turn whatever the choice is into a string if processor is None: processor = lambda x: utils.asciidammit(x) # default: wratio if scorer is None: scorer = WRatio sl = list() for choice in choices: processed = processor(choice) score = scorer(query, processed) tuple = (choice, score) sl.append(tuple) sl.sort(key=lambda i: -1*i[1]) return sl[:limit] ########################## # Find Single Best Match # ########################## def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0): # convenience method which returns the single best choice # optional parameter: score_cutoff. # If the best choice has a score of less than score_cutoff # we will return none (intuition: not a good enough match) best_list = extract(query, choices, processor, scorer, limit=1) if len(best_list) > 0: best = best_list[0] if best[1] > score_cutoff: return best else: return None else: return None
Python
#!/usr/bin/env python # encoding: utf-8 """ StringMatcher.py ported from python-Levenshtein [https://github.com/miohtama/python-Levenshtein] """ from Levenshtein import * from warnings import warn class StringMatcher: """A SequenceMatcher-like class built on the top of Levenshtein""" def _reset_cache(self): self._ratio = self._distance = None self._opcodes = self._editops = self._matching_blocks = None def __init__(self, isjunk=None, seq1='', seq2=''): if isjunk: warn("isjunk not NOT implemented, it will be ignored") self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seqs(self, seq1, seq2): self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seq1(self, seq1): self._str1 = seq1 self._reset_cache() def set_seq2(self, seq2): self._str2 = seq2 self._reset_cache() def get_opcodes(self): if not self._opcodes: if self._editops: self._opcodes = opcodes(self._editops, self._str1, self._str2) else: self._opcodes = opcodes(self._str1, self._str2) return self._opcodes def get_editops(self): if not self._editops: if self._opcodes: self._editops = editops(self._opcodes, self._str1, self._str2) else: self._editops = editops(self._str1, self._str2) return self._editops def get_matching_blocks(self): if not self._matching_blocks: self._matching_blocks = matching_blocks(self.get_opcodes(), self._str1, self._str2) return self._matching_blocks def ratio(self): if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def quick_ratio(self): # This is usually quick enough :o) if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def real_quick_ratio(self): len1, len2 = len(self._str1), len(self._str2) return 2.0 * min(len1, len2) / (len1 + len2) def distance(self): if not self._distance: self._distance = distance(self._str1, self._str2) return self._distance
Python
#!/usr/bin/env python # encoding: utf-8 """ score.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import os import re from utils import * try: from StringMatcher import StringMatcher as SequenceMatcher except: from difflib import SequenceMatcher REG_TOKEN = re.compile("[\w\d]+") ########################### # Basic Scoring Functions # ########################### def ratio(s1, s2): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") m = SequenceMatcher(None, s1, s2) return intr(100 * m.ratio()) # todo: skip duplicate indexes for a little more speed def partial_ratio(s1, s2): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") if len(s1) <= len(s2): shorter = s1; longer = s2; else: shorter = s2; longer = s1 m = SequenceMatcher(None, shorter, longer) blocks = m.get_matching_blocks() # each block represents a sequence of matching characters in a string # of the form (idx_1, idx_2, len) # the best partial match will block align with at least one of those blocks # e.g. shorter = "abcd", longer = XXXbcdeEEE # block = (1,3,3) # best score === ratio("abcd", "Xbcd") scores = [] for block in blocks: long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0 long_end = long_start + len(shorter) long_substr = longer[long_start:long_end] m2 = SequenceMatcher(None, shorter, long_substr) r = m2.ratio() if r > .995: return 100 else: scores.append(r) return int(100 * max(scores)) ############################## # Advanced Scoring Functions # ############################## # Sorted Token # find all alphanumeric tokens in the string # sort those tokens and take ratio of resulting joined strings # controls for unordered string elements def _token_sort(s1, s2, partial=True): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") # pull tokens tokens1 = REG_TOKEN.findall(s1) tokens2 = REG_TOKEN.findall(s2) # sort tokens and join sorted1 = u" ".join(sorted(tokens1)) sorted2 = u" ".join(sorted(tokens2)) sorted1 = sorted1.strip() sorted2 = sorted2.strip() if partial: return partial_ratio(sorted1, sorted2) else: return ratio(sorted1, sorted2) def token_sort_ratio(s1, s2): return _token_sort(s1, s2, False) def partial_token_sort_ratio(s1, s2): return _token_sort(s1, s2, True) # Token Set # find all alphanumeric tokens in each string...treat them as a set # construct two strings of the form # <sorted_intersection><sorted_remainder> # take ratios of those two strings # controls for unordered partial matches def _token_set(s1, s2, partial=True): if s1 is None: raise TypeError("s1 is None") if s2 is None: raise TypeError("s2 is None") # pull tokens tokens1 = set(REG_TOKEN.findall(s1)) tokens2 = set(REG_TOKEN.findall(s2)) intersection = tokens1.intersection(tokens2) diff1to2 = tokens1.difference(tokens2) diff2to1 = tokens2.difference(tokens1) sorted_sect = u" ".join(sorted(intersection)) sorted_1to2 = u" ".join(sorted(diff1to2)) sorted_2to1 = u" ".join(sorted(diff2to1)) combined_1to2 = sorted_sect + " " + sorted_1to2 combined_2to1 = sorted_sect + " " + sorted_2to1 # strip sorted_sect = sorted_sect.strip() combined_1to2 = combined_1to2.strip() combined_2to1 = combined_2to1.strip() pairwise = [ ratio(sorted_sect, combined_1to2), ratio(sorted_sect, combined_2to1), ratio(combined_1to2, combined_2to1) ] return max(pairwise) # if partial: # # partial_token_set_ratio # # else: # # token_set_ratio # tsr = ratio(combined_1to2, combined_2to1) # return tsr def token_set_ratio(s1, s2): return _token_set(s1, s2, False) def partial_token_set_ratio(s1, s2): return _token_set(s1, s2, True) # TODO: numerics ################### # Combination API # ################### # q is for quick def QRatio(s1, s2): if not validate_string(s1): return 0 if not validate_string(s2): return 0 p1 = full_process(s1) p2 = full_process(s2) return ratio(p1, p2) # w is for weighted def WRatio(s1, s2): p1 = full_process(s1) p2 = full_process(s2) if not validate_string(p1): return 0 if not validate_string(p2): return 0 # should we look at partials? try_partial = True unbase_scale = .95 partial_scale = .90 base = ratio(p1, p2) len_ratio = float(max(len(p1),len(p2)))/min(len(p1),len(p2)) # if strings are similar length, don't use partials if len_ratio < 1.5: try_partial = False # if one string is much much shorter than the other if len_ratio > 8: partial_scale = .6 if try_partial: partial = partial_ratio(p1, p2) * partial_scale ptsor = partial_token_sort_ratio(p1, p2) * unbase_scale * partial_scale ptser = partial_token_set_ratio(p1, p2) * unbase_scale * partial_scale return int(max(base, partial, ptsor, ptser)) else: tsor = token_sort_ratio(p1, p2) * unbase_scale tser = token_set_ratio(p1, p2) * unbase_scale return int(max(base, tsor, tser))
Python
from distutils.core import setup setup(name='fuzzywuzzy', version='0.1', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'])
Python
# -*- coding: utf8 -*- from timeit import timeit from fuzzywuzzy import utils iterations=100000 cirque_strings = [ "cirque du soleil - zarkana - las vegas", "cirque du soleil ", "cirque du soleil las vegas", "zarkana las vegas", "las vegas cirque du soleil at the bellagio", "zarakana - cirque du soleil - bellagio" ] choices = [ "", "new york yankees vs boston red sox", "", "zarakana - cirque du soleil - bellagio", None, "cirque du soleil las vegas", None ] mixed_strings = [ "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", "C\\'est la vie", "Ça va?", "Cães danados", u"\xacCamarões assados", u"a\xac\u1234\u20ac\U00008000" ] for s in choices: print 'Test for string: "%s"' % s # print 'Old: %f' % round(timeit('utils.validate_stringold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) print 'New: %f' % round(timeit('utils.validate_string(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) print for s in mixed_strings: print 'Test for string: "%s"' % s #print 'Old: %f' % round(timeit('utils.asciidammitold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) print 'New: %f' % round(timeit('utils.asciidammit(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) print for s in mixed_strings+cirque_strings+choices: print 'Test for string: "%s"' % s #print 'Old: %f' % round(timeit('utils.full_processold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) print 'New: %f' % round(timeit('utils.full_process(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4) ### benchmarking the core matching methods... for s in cirque_strings: print 'Test fuzz.ratio for string: "%s"' % s print '-------------------------------' print 'New: %f' % round(timeit('fuzz.ratio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4) for s in cirque_strings: print 'Test fuzz.partial_ratio for string: "%s"' % s print '-------------------------------' print 'New: %f' % round(timeit('fuzz.partial_ratio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4) for s in cirque_strings: print 'Test fuzz.WRatio for string: "%s"' % s print '-------------------------------' print 'New: %f' % round(timeit('fuzz.WRatio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4)
Python
#!/opt/ActivePython-2.7/bin/python ##################################################################################################### # Nicholas Harner # CSE411 # Homework 7 # 11/19/2012 # This program is an exact mimic of Coelacanth: a simple password generator. It is a very simple # application for creating passwords that can be used securely. Coelacanth was originally written # in C#. My version is written in python, using Tkinter for the GUI. This program allows the user # to designate if he/she would like a password containing any combination of uppercase letters, # lowercase letters, or digits. The user can also request that the password be copied to the clipboard # in windows following password generation. In addition, the user can specify the length of the # password to be generated. Upon clicking generate, the password is created using the user # specifications. Upon clicking clear, the text box containing the generated password is cleared. # This clear does not clear the clipboard however. #To Run on Suns, type: # python NickHarnerHW7.py # Coelacanth can be found at: # http://code.google.com/p/coelacanth/ ##################################################################################################### import os,sys import math import random #need this to create random password from Tkinter import * def fatal(): sys.exit() class Application(Frame): """ GUI application that creates a new random password based on user specs """ def __init__(self, master): Frame.__init__(self, master) self.grid(ipadx = 5, ipady = 2) #add some padding to make the GUI look nice self.create_widgets() #create all those buttons and other things you see in GUI def create_widgets(self): """ Create widgets to get new password user specs and to display the password. """ # create uppercase check button self.is_uppercase = BooleanVar() Checkbutton(self, text = "Uppercase", variable = self.is_uppercase ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create lowercase check button self.is_lowercase = BooleanVar() Checkbutton(self, text = "Lowercase", variable = self.is_lowercase ).grid(row = 1, column = 0, columnspan = 2, sticky = W) # create clipboard check button self.is_clipboard = BooleanVar() Checkbutton(self, text = "Clipboard", variable = self.is_clipboard ).grid(row = 0, column = 2, columnspan = 2, sticky = W) # create digit check button self.is_digit = BooleanVar() Checkbutton(self, text = "Digits", variable = self.is_digit ).grid(row = 2, column = 0, columnspan = 2, sticky = W) # create password label for spinbox self.pass_length = StringVar() self.previous_pass_length = StringVar() Label(self, text = "Length" ).grid(row = 2, column = 2, sticky = W) # create password length spinbox vcmd = (self.register(self.validate_float), '%s', '%P') #create validation command for spinbox monitoring self.spinbox = Spinbox(self, textvariable = self.pass_length, from_=1, to=20, width = 6, validate="key", validatecommand = vcmd) #checks for validation upon key entry self.spinbox.grid(row = 2, column = 2, columnspan = 1, sticky = E) # create a generate button Button(self, text = "Generate", height = 1, width = 10, command = self.get_password ).grid(row = 3, column = 0, columnspan = 2, sticky = N, pady = 2, padx = 5) # create a clear button for password text box Button(self, text = "Clear", height = 1, width = 10, command = self.clear_password ).grid(row = 3, column = 2, columnspan = 2, sticky = W, pady = 2, padx = 5) # create a text box label for generated password Label(self, text = "Password" ).grid(row = 4, column = 0, columnspan = 1, sticky = E, pady = 5) # create a text box for generated password self.password_txt = Text(self, width = 21, height = 1, wrap = NONE) self.password_txt.grid(row = 4, column = 2, columnspan = 2,sticky = S, pady = 5) # set all check buttons to checked initially # also set default password length to 8 self.is_digit.set(True) self.is_clipboard.set(True) self.is_uppercase.set(True) self.is_lowercase.set(True) self.pass_length.set('8') # validate spinbox entries def validate_float(self, previous, new): """ Validate the spinbox entry for only float values. """ if new == "" or new == "-": return True #check to see if the input is a float try: float(new) self.previous_pass_length.set(new) #record most up-to-date valid input return True except ValueError: return False # clear password text box def clear_password(self): """ Clear text box with generated password. """ self.password_txt.delete(0.0, END) # get password from entered specifications def get_password(self): """ Fill password text box with new password based on user specs. """ #convert all entered decimal numbers into the next integer passwordLength = int(math.ceil(float(self.previous_pass_length.get()))) # get values from the GUI digit = self.is_digit.get() uppercase = self.is_uppercase.get() lowercase = self.is_lowercase.get() clipboard = self.is_clipboard.get() # reset value in GUI to converted passwordLength self.pass_length.set(passwordLength) # If the user overrides the spinbox and enters a number manually, set values to closest option if passwordLength > 20: passwordLength = 20 self.pass_length.set('20') if passwordLength < 1: passwordLength = 1 self.pass_length.set('1') # generate password g = passwordGenerator(passwordLength,digit,uppercase,lowercase,clipboard) password = g.createPassword() # print password to text box self.clear_password() self.password_txt.insert(END, g.printPassword(password)) ##################################################################################################### class passwordGenerator: """A class for generating a password""" def __init__(self,passwordLength,digit,uppercase,lowercase,clipboard): self.pwdLength = int(passwordLength) #convert all these boolean and string vars to integers for use self.dig = int(digit) self.upper = int(uppercase) self.lower = int(lowercase) self.clip = int(clipboard) self.noChoices = 0 # this function chooses random characters based on user input and returns them as a list def createPassword(self): """ Create password based on user specs. """ #initialize list passwordCharList = [] pwd = [] #define letters and digits lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz' uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' # make digits an option when randomly selecting a char (user must specify) if self.dig: passwordCharList.extend(list(digits)) # make uppercase letters an option when randomly selecting a char (user must specify) if self.upper: passwordCharList.extend(list(uppercaseLetters)) # make lowercase letters an option when randomly selecting a char (user must specify) if self.lower: passwordCharList.extend(list(lowercaseLetters)) # choose random characters from option above (number of choices depends on password length) if self.dig or self.upper or self.lower: pwd = self.sample_with_replacement(passwordCharList,self.pwdLength) else: self.noChoices = 1 #record when no options are selected return pwd #This function a random sample list from a given list and the number of choices requested #NOTE: This is sampling with replacement, so digits and letters can repeat in a password def sample_with_replacement(self, popList, numChoices): """ Sample a list with replacement. """ passwordList = [] # select random characters for password for x in range(0,numChoices): passwordList.extend(random.sample(popList,1)) return passwordList #This function returns the string form of a given password character list def printPassword(self,pwd): """ Convert list to string and copy to clipboard if required. """ #set generic empty password stringPassword = "" #only create new password if there are characters to choose from if self.noChoices != 1: # add characters in password list to password string for x in range(0,self.pwdLength): stringPassword += pwd[x] # add password to clipboard if user specified to do that if self.clip: c = Tk() c.withdraw() c.clipboard_clear() c.clipboard_append(stringPassword) c.destroy() return stringPassword ##################################################################################################### # the main program root = Tk() root.title("Coelacanth") app = Application(root) root.mainloop()
Python
#!/usr/bin/python # Sean Hill # Fall 2012 # CSE 411 # Homework 7 # # Description: Translates the image segmentation code from the following website from C++ to Python: # http://www.cs.brown.edu/~pff/segment/ # # Instructions: The command-line usage is as follows, where "sigma" and "k" and "min" are # algorithm parameters, "input" is the .ppm file to be segmented, and "output" is a .ppm # file for storing the output: # H7.py sigma k min input output # The output file doesn't need to exist, and the input file must be in a special ppm format # that starts with P6. See http://orion.math.iastate.edu/burkardt/data/ppm/ppm.html for more # information and http://www.cs.cornell.edu/courses/cs664/2003fa/images/ for more sample # input files. Here's an example to run the program using the files I provided: # H7.py .5 500 50 sign_1.ppm output.ppm import sys, math, random, struct MAXVAL = 255 # maximum allowed third value in P6 ppm file WIDTH = 4.0 # used in filter calculations # ------------------------------------------------------- # pnmfile.h # ------------------------------------------------------- def error(message): """ Report pnm_error and exit. """ sys.stderr.write("ERROR: " + message + " Exiting.\n") sys.exit() def pnm_read(f): """ Read a line of the PNM field, skipping comments. """ c = f.read(1) while c == '#': f.readline() c = f.read(1) f.seek(-1, 1) ret = f.readline() return ret def loadPPM(filename): """ Load a PPM image from the specified input file into an Image class instance and rturn it. """ # read header: try: f = open(filename, "rb") except IOError: error("Failed to open file " + filename + ".") buf = pnm_read(f) if (buf[0:2] != "P6"): error("P6 not found in header of file " + filename + ".") buf = pnm_read(f).strip().split() width = int(buf[0]) height = int(buf[1]) buf = pnm_read(f) if (int(buf) > MAXVAL): error("Max value (third number after P6) in file " + filename + " exceeds maximum allowed value of " + str(MAXVAL) + ".") im = Image(width, height, 3) # read in pixel values, convert from single bytes to rgb string lists: for y in range(height): for x in range(width): rgb = [] for i in range(3): rgb.append(f.read(1)) im.set_binary_data(x, y, rgb) f.close() return im def savePPM(im, filename): width = im.width height = im.height try: f = open(filename, "wb") except IOError: error("Failed to open file " + filename + ".") f.write("P6\n" + str(width) + ' ' + str(height) + '\n' + str(MAXVAL) + '\n') for y in range(height): for x in range(width): rgb = im.get_binary_data(x, y) f.write(rgb[0] + rgb[1] + rgb[2]) f.close() # ------------------------------------------------------- # image.h # ------------------------------------------------------- class Image: def __init__(self, width, height, depth): self.width = width self.height = height self.depth = depth # 3 for full image, 1 for segment self.data = [[0.0 for value in range(depth)] for value in range(width * height)] def set_binary_data(self, x, y, input_data): """ Set data at (x, y) from binary-form input of a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: self.data[loc] = struct.unpack('B', input_data)[0] else: self.data[loc] = [struct.unpack('B', input_data[i])[0] for i in range(self.depth)] def set_decimal_data(self, x, y, input_data): """ Set data at (x, y) from decimal-form input of a single element or a list of size self.depth. """ loc = y * self.width + x self.data[loc] = input_data def get_binary_data(self, x, y): """ Return data at (x, y) in binary form as a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: return struct.pack('B', int(self.data[loc])) else: return [struct.pack('B', int(self.data[loc][i])) for i in range(self.depth)] def get_decimal_data(self, x, y): """ Return data at (x, y) in decimal form as a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: return self.data[loc] else: return [self.data[loc][i] for i in range(self.depth)] # ------------------------------------------------------- # segment-image.h # ------------------------------------------------------- def random_rgb(): rgb = [] for i in range(3): rgb.append(random.randrange(0, 256)) return rgb def diff(r, g, b, x1, y1, x2, y2): return math.sqrt(pow(r.get_decimal_data(x1, y1) - r.get_decimal_data(x2, y2), 2) + \ pow(g.get_decimal_data(x1, y1) - g.get_decimal_data(x2, y2), 2) + \ pow(b.get_decimal_data(x1, y1) - b.get_decimal_data(x2, y2), 2)) def segment_image(im, sigma, c, min_size): """ Segment an image. Returns a color image representing the segmentation and the number of components in the segmentation. img: image to segment sigma: to smooth the image c: constant for threshold function min_size: minimum component size (enforced by post-processing stage)""" width = im.width height = im.height # separate colors into three channels: r = Image(width, height, 1) g = Image(width, height, 1) b = Image(width, height, 1) for y in range(height): for x in range(width): rgb = im.get_decimal_data(x, y) r.set_decimal_data(x, y, rgb[0]) g.set_decimal_data(x, y, rgb[1]) b.set_decimal_data(x, y, rgb[2]) # smooth each color channel: smooth_r = smooth(r, sigma) smooth_g = smooth(g, sigma) smooth_b = smooth(b, sigma) # build graph: edges = [] num = 0 for y in range(height): for x in range(width): if x < width - 1: edges.append(Edge(y * width + x, \ y * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y))) if y < height - 1: edges.append(Edge(y * width + x, \ (y + 1) * width + x, \ diff(smooth_r, smooth_g, smooth_b, x, y, x, y + 1))) if x < width - 1 and y < height - 1: edges.append(Edge(y * width + x, \ (y + 1) * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y + 1))) if x < width - 1 and y > 0: edges.append(Edge(y * width + x, \ (y - 1) * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y - 1))) while len(edges) < width * height * 4: edges.append(Edge(0, 0, 0)) # segment: u = segment_graph(width * height, edges, c) # post-process small components: for i in range(len(edges)): a = u.find(edges[i].a) b = u.find(edges[i].b) if a != b and (u.size(a) < min_size or u.size(b) < min_size): u.join(a, b) num_ccs = u.num_sets() output = Image(width, height, 3) # pick random colors for each component: colors = [random_rgb() for value in range(width * height)] for y in range(height): for x in range(height): comp = u.find(y * width + x) output.set_decimal_data(x, y, colors[comp]) return output, num_ccs # ------------------------------------------------------- # filter.h # ------------------------------------------------------- def normalize(mask): """ Normalize mask so it integrates to one. """ length = len(mask) sum = 0.0 for i in range(1, length): sum = sum + math.fabs(mask[i]) sum = 2 * sum + math.fabs(mask[0]) for i in range(length): mask[i] = mask[i] / sum return mask def make_fgauss(sigma): sigma = max((sigma, 0.01)) length = int(math.ceil(sigma * WIDTH) + 1) mask = [0.0 for value in range(length)] for i in range(length): mask[i] = math.exp(-0.5 * math.pow(i/sigma, 2)) return mask def smooth(src, sigma): """ Convolve image with gaussian filter. """ mask = make_fgauss(sigma) mask = normalize(mask) tmp = convolve_even(src, mask) dst = convolve_even(tmp, mask) return dst # ------------------------------------------------------- # convolve.h # ------------------------------------------------------- def convolve_even(src, mask): """ Convolve src with mask. ret is flipped! """ width = src.width height = src.height length = len(mask) ret = Image(src.height, src.width, 1) for y in range(height): for x in range(width): sum = mask[0] * src.get_decimal_data(x, y) for i in range(1, length): sum = sum + mask[i] \ * (src.get_decimal_data(max((x - i, 0)), y) \ + src.get_decimal_data(min((x + i, width - 1)), y)) ret.set_decimal_data(y, x, sum) return ret # ------------------------------------------------------- # segment-graph.h # ------------------------------------------------------- def segment_graph(num_vertices, edges, c): """ Segment a graph. Returns a disjoint-set forest representing the segmentation. num_vertices: number of vertices in graph edges: array of edges c: constant for treshold function""" # sort edges by weight: edges = sorted(edges) # make a disjoint-set forest: u = Universe(num_vertices) # initiate thresholds: threshold = [c for value in range(num_vertices)] # for each edge, in non-decreasing weight order: for i in range(len(edges)): # components connected by this edge: a = u.find(edges[i].a) b = u.find(edges[i].b) if a != b: if edges[i].w <= threshold[a] and edges[i].w <= threshold[b]: u.join(a, b) a = u.find(a) threshold[a] = edges[i].w + (c / u.size(a)) return u class Edge: def __init__(self, a, b, w): self.a = a self.b = b self.w = w # ------------------------------------------------------- # disjoint-set.h # ------------------------------------------------------- class Uni_elt: """ Universe element. """ def __init__(self, rank, size, p): self.rank = rank self.size = size self.p = p class Universe: def __init__(self, elements): self.elts = [Uni_elt(0, 1, i) for i in range(elements)] self.num = elements def find(self, x): y = x while y != self.elts[y].p: y = self.elts[y].p self.elts[x].p = y return y def join(self, x, y): if self.elts[x].rank > self.elts[y].rank: self.elts[y].p = x self.elts[x].size = self.elts[x].size + self.elts[y].size else: self.elts[x].p = y self.elts[y].size = self.elts[y].size + self.elts[x].size if self.elts[x].rank == self.elts[y].rank: self.elts[y].rank = self.elts[y].rank + 1 self.num = self.num - 1 def size(self, x): return self.elts[x].size def num_sets(self): return self.num # ------------------------------------------------------- # segment.cpp (main method) # ------------------------------------------------------- if (len(sys.argv) != 6): sys.stderr.write("usage: " + sys.argv[0] + " sigma k min input(ppm) output(ppm)\n") sys.exit() sigma = float(sys.argv[1]) k = float(sys.argv[2]) min_size = int(sys.argv[3]) print("loading input image.") input_image = loadPPM(sys.argv[4]) print("processing") seg, num_ccs = segment_image(input_image, sigma, k, min_size) # return two values savePPM(seg, sys.argv[5]) print "got", num_ccs, "components" print "done! uff...thats hard work."
Python
#! /usr/bin/python from optparse import OptionParser import os.path import sys parser = OptionParser() parser.add_option("-L", "--line", dest="stripLine", action="store_true", default=False, help="strip single-line comments //...\\n") parser.add_option("-C", "--cstyle", dest="stripCStyle", action="store_true", default=False, help="strip C-style comments /*...*/") parser.add_option("-J", "--javadoc", dest="stripJavadoc", action="store_true", default=False, help="strip Javadoc comments /**...*/") parser.add_option("-H", "--headerdoc", dest="stripHeaderDoc", action="store_true", default=False, help="strip HeaderDoc comments /*!...*/") parser.add_option("--input", dest="inputFile", default="", help="file from which to read input") (options, args) = parser.parse_args() error = False if len(args) != 0: print "ERROR: Invalid non-option arguments:" for arg in args: print " "+arg error = True if not options.stripLine and not options.stripCStyle and \ not options.stripJavadoc and not options.stripHeaderDoc: print "ERROR: Please specify at least one comment style to strip." error = True if options.inputFile == "": print "ERROR: Must specify input file to process using '--input'." error = True elif os.path.exists(options.inputFile) == False: print "ERROR: Specified input file does not exist!" error = True else: file = open(options.inputFile, "r") if error == True: sys.exit() (SOURCE, STRING_LITERAL, CHAR_LITERAL, SLASH, SLASH_STAR, COMMENT_LINE, COMMENT_CSTYLE, COMMENT_JAVADOC, COMMENT_HEADERDOC) = range(9) #state constants state = SOURCE thisChar = '' while (1): prevChar = thisChar thisChar = file.read(1) if not thisChar: break if state == SOURCE: if thisChar == '/': state = SLASH else: if thisChar == '"': state = STRING_LITERAL elif thisChar == '\'': state = CHAR_LITERAL sys.stdout.write(thisChar) elif state == STRING_LITERAL: if thisChar == '"' and prevChar != '\\': state = SOURCE sys.stdout.write(thisChar) elif state == CHAR_LITERAL: if thisChar == '\'' and prevChar != '\\': state = SOURCE sys.stdout.write(thisChar) elif state == SLASH: if thisChar == '*': state = SLASH_STAR elif thisChar == '/': if not options.stripLine: sys.stdout.write("//") state = COMMENT_LINE else: sys.stdout.write("/") sys.stdout.write(thisChar) state = SOURCE elif state == SLASH_STAR: if thisChar == '*': if not options.stripJavadoc: sys.stdout.write("/**") state = COMMENT_JAVADOC elif thisChar == '!': if not options.stripHeaderDoc: sys.stdout.write("/*!") state = COMMENT_HEADERDOC else: if not options.stripCStyle: sys.stdout.write("/*") sys.stdout.write(thisChar) state = COMMENT_CSTYLE thisChar = 0 # Don't treat "/*/" as a valid block comment elif state == COMMENT_LINE: if thisChar == '\n': sys.stdout.write("\n") state = SOURCE if not options.stripLine: sys.stdout.write(thisChar) elif state == COMMENT_CSTYLE: if not options.stripCStyle: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE elif state == COMMENT_JAVADOC: if not options.stripJavadoc: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE elif state == COMMENT_HEADERDOC: if not options.stripHeaderDoc: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE file.close()
Python
#!/opt/ActivePython-2.7/bin/python ##################################################################################################### # Nicholas Harner # CSE411 # Homework 7 # 11/19/2012 # This program is an exact mimic of Coelacanth: a simple password generator. It is a very simple # application for creating passwords that can be used securely. Coelacanth was originally written # in C#. My version is written in python, using Tkinter for the GUI. This program allows the user # to designate if he/she would like a password containing any combination of uppercase letters, # lowercase letters, or digits. The user can also request that the password be copied to the clipboard # in windows following password generation. In addition, the user can specify the length of the # password to be generated. Upon clicking generate, the password is created using the user # specifications. Upon clicking clear, the text box containing the generated password is cleared. # This clear does not clear the clipboard however. #To Run on Suns, type: # python NickHarnerHW7.py # Coelacanth can be found at: # http://code.google.com/p/coelacanth/ ##################################################################################################### import os,sys import math import random #need this to create random password from Tkinter import * def fatal(): sys.exit() class Application(Frame): """ GUI application that creates a new random password based on user specs """ def __init__(self, master): Frame.__init__(self, master) self.grid(ipadx = 5, ipady = 2) #add some padding to make the GUI look nice self.create_widgets() #create all those buttons and other things you see in GUI def create_widgets(self): """ Create widgets to get new password user specs and to display the password. """ # create uppercase check button self.is_uppercase = BooleanVar() Checkbutton(self, text = "Uppercase", variable = self.is_uppercase ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create lowercase check button self.is_lowercase = BooleanVar() Checkbutton(self, text = "Lowercase", variable = self.is_lowercase ).grid(row = 1, column = 0, columnspan = 2, sticky = W) # create clipboard check button self.is_clipboard = BooleanVar() Checkbutton(self, text = "Clipboard", variable = self.is_clipboard ).grid(row = 0, column = 2, columnspan = 2, sticky = W) # create digit check button self.is_digit = BooleanVar() Checkbutton(self, text = "Digits", variable = self.is_digit ).grid(row = 2, column = 0, columnspan = 2, sticky = W) # create password label for spinbox self.pass_length = StringVar() self.previous_pass_length = StringVar() Label(self, text = "Length" ).grid(row = 2, column = 2, sticky = W) # create password length spinbox vcmd = (self.register(self.validate_float), '%s', '%P') #create validation command for spinbox monitoring self.spinbox = Spinbox(self, textvariable = self.pass_length, from_=1, to=20, width = 6, validate="key", validatecommand = vcmd) #checks for validation upon key entry self.spinbox.grid(row = 2, column = 2, columnspan = 1, sticky = E) # create a generate button Button(self, text = "Generate", height = 1, width = 10, command = self.get_password ).grid(row = 3, column = 0, columnspan = 2, sticky = N, pady = 2, padx = 5) # create a clear button for password text box Button(self, text = "Clear", height = 1, width = 10, command = self.clear_password ).grid(row = 3, column = 2, columnspan = 2, sticky = W, pady = 2, padx = 5) # create a text box label for generated password Label(self, text = "Password" ).grid(row = 4, column = 0, columnspan = 1, sticky = E, pady = 5) # create a text box for generated password self.password_txt = Text(self, width = 21, height = 1, wrap = NONE) self.password_txt.grid(row = 4, column = 2, columnspan = 2,sticky = S, pady = 5) # set all check buttons to checked initially # also set default password length to 8 self.is_digit.set(True) self.is_clipboard.set(True) self.is_uppercase.set(True) self.is_lowercase.set(True) self.pass_length.set('8') # validate spinbox entries def validate_float(self, previous, new): """ Validate the spinbox entry for only float values. """ if new == "" or new == "-": return True #check to see if the input is a float try: float(new) self.previous_pass_length.set(new) #record most up-to-date valid input return True except ValueError: return False # clear password text box def clear_password(self): """ Clear text box with generated password. """ self.password_txt.delete(0.0, END) # get password from entered specifications def get_password(self): """ Fill password text box with new password based on user specs. """ #convert all entered decimal numbers into the next integer passwordLength = int(math.ceil(float(self.previous_pass_length.get()))) # get values from the GUI digit = self.is_digit.get() uppercase = self.is_uppercase.get() lowercase = self.is_lowercase.get() clipboard = self.is_clipboard.get() # reset value in GUI to converted passwordLength self.pass_length.set(passwordLength) # If the user overrides the spinbox and enters a number manually, set values to closest option if passwordLength > 20: passwordLength = 20 self.pass_length.set('20') if passwordLength < 1: passwordLength = 1 self.pass_length.set('1') # generate password g = passwordGenerator(passwordLength,digit,uppercase,lowercase,clipboard) password = g.createPassword() # print password to text box self.clear_password() self.password_txt.insert(END, g.printPassword(password)) ##################################################################################################### class passwordGenerator: """A class for generating a password""" def __init__(self,passwordLength,digit,uppercase,lowercase,clipboard): self.pwdLength = int(passwordLength) #convert all these boolean and string vars to integers for use self.dig = int(digit) self.upper = int(uppercase) self.lower = int(lowercase) self.clip = int(clipboard) self.noChoices = 0 # this function chooses random characters based on user input and returns them as a list def createPassword(self): """ Create password based on user specs. """ #initialize list passwordCharList = [] pwd = [] #define letters and digits lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz' uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' # make digits an option when randomly selecting a char (user must specify) if self.dig: passwordCharList.extend(list(digits)) # make uppercase letters an option when randomly selecting a char (user must specify) if self.upper: passwordCharList.extend(list(uppercaseLetters)) # make lowercase letters an option when randomly selecting a char (user must specify) if self.lower: passwordCharList.extend(list(lowercaseLetters)) # choose random characters from option above (number of choices depends on password length) if self.dig or self.upper or self.lower: pwd = self.sample_with_replacement(passwordCharList,self.pwdLength) else: self.noChoices = 1 #record when no options are selected return pwd #This function a random sample list from a given list and the number of choices requested #NOTE: This is sampling with replacement, so digits and letters can repeat in a password def sample_with_replacement(self, popList, numChoices): """ Sample a list with replacement. """ passwordList = [] # select random characters for password for x in range(0,numChoices): passwordList.extend(random.sample(popList,1)) return passwordList #This function returns the string form of a given password character list def printPassword(self,pwd): """ Convert list to string and copy to clipboard if required. """ #set generic empty password stringPassword = "" #only create new password if there are characters to choose from if self.noChoices != 1: # add characters in password list to password string for x in range(0,self.pwdLength): stringPassword += pwd[x] # add password to clipboard if user specified to do that if self.clip: c = Tk() c.withdraw() c.clipboard_clear() c.clipboard_append(stringPassword) c.destroy() return stringPassword ##################################################################################################### # the main program root = Tk() root.title("Coelacanth") app = Application(root) root.mainloop()
Python
#!/usr/bin/python # Sean Hill # Fall 2012 # CSE 411 # Homework 7 # # Description: Translates the image segmentation code from the following website from C++ to Python: # http://www.cs.brown.edu/~pff/segment/ # # Instructions: The command-line usage is as follows, where "sigma" and "k" and "min" are # algorithm parameters, "input" is the .ppm file to be segmented, and "output" is a .ppm # file for storing the output: # H7.py sigma k min input output # The output file doesn't need to exist, and the input file must be in a special ppm format # that starts with P6. See http://orion.math.iastate.edu/burkardt/data/ppm/ppm.html for more # information and http://www.cs.cornell.edu/courses/cs664/2003fa/images/ for more sample # input files. Here's an example to run the program using the files I provided: # H7.py .5 500 50 sign_1.ppm output.ppm import sys, math, random, struct MAXVAL = 255 # maximum allowed third value in P6 ppm file WIDTH = 4.0 # used in filter calculations # ------------------------------------------------------- # pnmfile.h # ------------------------------------------------------- def error(message): """ Report pnm_error and exit. """ sys.stderr.write("ERROR: " + message + " Exiting.\n") sys.exit() def pnm_read(f): """ Read a line of the PNM field, skipping comments. """ c = f.read(1) while c == '#': f.readline() c = f.read(1) f.seek(-1, 1) ret = f.readline() return ret def loadPPM(filename): """ Load a PPM image from the specified input file into an Image class instance and rturn it. """ # read header: try: f = open(filename, "rb") except IOError: error("Failed to open file " + filename + ".") buf = pnm_read(f) if (buf[0:2] != "P6"): error("P6 not found in header of file " + filename + ".") buf = pnm_read(f).strip().split() width = int(buf[0]) height = int(buf[1]) buf = pnm_read(f) if (int(buf) > MAXVAL): error("Max value (third number after P6) in file " + filename + " exceeds maximum allowed value of " + str(MAXVAL) + ".") im = Image(width, height, 3) # read in pixel values, convert from single bytes to rgb string lists: for y in range(height): for x in range(width): rgb = [] for i in range(3): rgb.append(f.read(1)) im.set_binary_data(x, y, rgb) f.close() return im def savePPM(im, filename): width = im.width height = im.height try: f = open(filename, "wb") except IOError: error("Failed to open file " + filename + ".") f.write("P6\n" + str(width) + ' ' + str(height) + '\n' + str(MAXVAL) + '\n') for y in range(height): for x in range(width): rgb = im.get_binary_data(x, y) f.write(rgb[0] + rgb[1] + rgb[2]) f.close() # ------------------------------------------------------- # image.h # ------------------------------------------------------- class Image: def __init__(self, width, height, depth): self.width = width self.height = height self.depth = depth # 3 for full image, 1 for segment self.data = [[0.0 for value in range(depth)] for value in range(width * height)] def set_binary_data(self, x, y, input_data): """ Set data at (x, y) from binary-form input of a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: self.data[loc] = struct.unpack('B', input_data)[0] else: self.data[loc] = [struct.unpack('B', input_data[i])[0] for i in range(self.depth)] def set_decimal_data(self, x, y, input_data): """ Set data at (x, y) from decimal-form input of a single element or a list of size self.depth. """ loc = y * self.width + x self.data[loc] = input_data def get_binary_data(self, x, y): """ Return data at (x, y) in binary form as a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: return struct.pack('B', int(self.data[loc])) else: return [struct.pack('B', int(self.data[loc][i])) for i in range(self.depth)] def get_decimal_data(self, x, y): """ Return data at (x, y) in decimal form as a single element or a list of size self.depth. """ loc = y * self.width + x if self.depth == 1: return self.data[loc] else: return [self.data[loc][i] for i in range(self.depth)] # ------------------------------------------------------- # segment-image.h # ------------------------------------------------------- def random_rgb(): rgb = [] for i in range(3): rgb.append(random.randrange(0, 256)) return rgb def diff(r, g, b, x1, y1, x2, y2): return math.sqrt(pow(r.get_decimal_data(x1, y1) - r.get_decimal_data(x2, y2), 2) + \ pow(g.get_decimal_data(x1, y1) - g.get_decimal_data(x2, y2), 2) + \ pow(b.get_decimal_data(x1, y1) - b.get_decimal_data(x2, y2), 2)) def segment_image(im, sigma, c, min_size): """ Segment an image. Returns a color image representing the segmentation and the number of components in the segmentation. img: image to segment sigma: to smooth the image c: constant for threshold function min_size: minimum component size (enforced by post-processing stage)""" width = im.width height = im.height # separate colors into three channels: r = Image(width, height, 1) g = Image(width, height, 1) b = Image(width, height, 1) for y in range(height): for x in range(width): rgb = im.get_decimal_data(x, y) r.set_decimal_data(x, y, rgb[0]) g.set_decimal_data(x, y, rgb[1]) b.set_decimal_data(x, y, rgb[2]) # smooth each color channel: smooth_r = smooth(r, sigma) smooth_g = smooth(g, sigma) smooth_b = smooth(b, sigma) # build graph: edges = [] num = 0 for y in range(height): for x in range(width): if x < width - 1: edges.append(Edge(y * width + x, \ y * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y))) if y < height - 1: edges.append(Edge(y * width + x, \ (y + 1) * width + x, \ diff(smooth_r, smooth_g, smooth_b, x, y, x, y + 1))) if x < width - 1 and y < height - 1: edges.append(Edge(y * width + x, \ (y + 1) * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y + 1))) if x < width - 1 and y > 0: edges.append(Edge(y * width + x, \ (y - 1) * width + (x + 1), \ diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y - 1))) while len(edges) < width * height * 4: edges.append(Edge(0, 0, 0)) # segment: u = segment_graph(width * height, edges, c) # post-process small components: for i in range(len(edges)): a = u.find(edges[i].a) b = u.find(edges[i].b) if a != b and (u.size(a) < min_size or u.size(b) < min_size): u.join(a, b) num_ccs = u.num_sets() output = Image(width, height, 3) # pick random colors for each component: colors = [random_rgb() for value in range(width * height)] for y in range(height): for x in range(height): comp = u.find(y * width + x) output.set_decimal_data(x, y, colors[comp]) return output, num_ccs # ------------------------------------------------------- # filter.h # ------------------------------------------------------- def normalize(mask): """ Normalize mask so it integrates to one. """ length = len(mask) sum = 0.0 for i in range(1, length): sum = sum + math.fabs(mask[i]) sum = 2 * sum + math.fabs(mask[0]) for i in range(length): mask[i] = mask[i] / sum return mask def make_fgauss(sigma): sigma = max((sigma, 0.01)) length = int(math.ceil(sigma * WIDTH) + 1) mask = [0.0 for value in range(length)] for i in range(length): mask[i] = math.exp(-0.5 * math.pow(i/sigma, 2)) return mask def smooth(src, sigma): """ Convolve image with gaussian filter. """ mask = make_fgauss(sigma) mask = normalize(mask) tmp = convolve_even(src, mask) dst = convolve_even(tmp, mask) return dst # ------------------------------------------------------- # convolve.h # ------------------------------------------------------- def convolve_even(src, mask): """ Convolve src with mask. ret is flipped! """ width = src.width height = src.height length = len(mask) ret = Image(src.height, src.width, 1) for y in range(height): for x in range(width): sum = mask[0] * src.get_decimal_data(x, y) for i in range(1, length): sum = sum + mask[i] \ * (src.get_decimal_data(max((x - i, 0)), y) \ + src.get_decimal_data(min((x + i, width - 1)), y)) ret.set_decimal_data(y, x, sum) return ret # ------------------------------------------------------- # segment-graph.h # ------------------------------------------------------- def segment_graph(num_vertices, edges, c): """ Segment a graph. Returns a disjoint-set forest representing the segmentation. num_vertices: number of vertices in graph edges: array of edges c: constant for treshold function""" # sort edges by weight: edges = sorted(edges) # make a disjoint-set forest: u = Universe(num_vertices) # initiate thresholds: threshold = [c for value in range(num_vertices)] # for each edge, in non-decreasing weight order: for i in range(len(edges)): # components connected by this edge: a = u.find(edges[i].a) b = u.find(edges[i].b) if a != b: if edges[i].w <= threshold[a] and edges[i].w <= threshold[b]: u.join(a, b) a = u.find(a) threshold[a] = edges[i].w + (c / u.size(a)) return u class Edge: def __init__(self, a, b, w): self.a = a self.b = b self.w = w # ------------------------------------------------------- # disjoint-set.h # ------------------------------------------------------- class Uni_elt: """ Universe element. """ def __init__(self, rank, size, p): self.rank = rank self.size = size self.p = p class Universe: def __init__(self, elements): self.elts = [Uni_elt(0, 1, i) for i in range(elements)] self.num = elements def find(self, x): y = x while y != self.elts[y].p: y = self.elts[y].p self.elts[x].p = y return y def join(self, x, y): if self.elts[x].rank > self.elts[y].rank: self.elts[y].p = x self.elts[x].size = self.elts[x].size + self.elts[y].size else: self.elts[x].p = y self.elts[y].size = self.elts[y].size + self.elts[x].size if self.elts[x].rank == self.elts[y].rank: self.elts[y].rank = self.elts[y].rank + 1 self.num = self.num - 1 def size(self, x): return self.elts[x].size def num_sets(self): return self.num # ------------------------------------------------------- # segment.cpp (main method) # ------------------------------------------------------- if (len(sys.argv) != 6): sys.stderr.write("usage: " + sys.argv[0] + " sigma k min input(ppm) output(ppm)\n") sys.exit() sigma = float(sys.argv[1]) k = float(sys.argv[2]) min_size = int(sys.argv[3]) print("loading input image.") input_image = loadPPM(sys.argv[4]) print("processing") seg, num_ccs = segment_image(input_image, sigma, k, min_size) # return two values savePPM(seg, sys.argv[5]) print "got", num_ccs, "components" print "done! uff...thats hard work."
Python
#! /usr/bin/python from optparse import OptionParser import os.path import sys parser = OptionParser() parser.add_option("-L", "--line", dest="stripLine", action="store_true", default=False, help="strip single-line comments //...\\n") parser.add_option("-C", "--cstyle", dest="stripCStyle", action="store_true", default=False, help="strip C-style comments /*...*/") parser.add_option("-J", "--javadoc", dest="stripJavadoc", action="store_true", default=False, help="strip Javadoc comments /**...*/") parser.add_option("-H", "--headerdoc", dest="stripHeaderDoc", action="store_true", default=False, help="strip HeaderDoc comments /*!...*/") parser.add_option("--input", dest="inputFile", default="", help="file from which to read input") (options, args) = parser.parse_args() error = False if len(args) != 0: print "ERROR: Invalid non-option arguments:" for arg in args: print " "+arg error = True if not options.stripLine and not options.stripCStyle and \ not options.stripJavadoc and not options.stripHeaderDoc: print "ERROR: Please specify at least one comment style to strip." error = True if options.inputFile == "": print "ERROR: Must specify input file to process using '--input'." error = True elif os.path.exists(options.inputFile) == False: print "ERROR: Specified input file does not exist!" error = True else: file = open(options.inputFile, "r") if error == True: sys.exit() (SOURCE, STRING_LITERAL, CHAR_LITERAL, SLASH, SLASH_STAR, COMMENT_LINE, COMMENT_CSTYLE, COMMENT_JAVADOC, COMMENT_HEADERDOC) = range(9) #state constants state = SOURCE thisChar = '' while (1): prevChar = thisChar thisChar = file.read(1) if not thisChar: break if state == SOURCE: if thisChar == '/': state = SLASH else: if thisChar == '"': state = STRING_LITERAL elif thisChar == '\'': state = CHAR_LITERAL sys.stdout.write(thisChar) elif state == STRING_LITERAL: if thisChar == '"' and prevChar != '\\': state = SOURCE sys.stdout.write(thisChar) elif state == CHAR_LITERAL: if thisChar == '\'' and prevChar != '\\': state = SOURCE sys.stdout.write(thisChar) elif state == SLASH: if thisChar == '*': state = SLASH_STAR elif thisChar == '/': if not options.stripLine: sys.stdout.write("//") state = COMMENT_LINE else: sys.stdout.write("/") sys.stdout.write(thisChar) state = SOURCE elif state == SLASH_STAR: if thisChar == '*': if not options.stripJavadoc: sys.stdout.write("/**") state = COMMENT_JAVADOC elif thisChar == '!': if not options.stripHeaderDoc: sys.stdout.write("/*!") state = COMMENT_HEADERDOC else: if not options.stripCStyle: sys.stdout.write("/*") sys.stdout.write(thisChar) state = COMMENT_CSTYLE thisChar = 0 # Don't treat "/*/" as a valid block comment elif state == COMMENT_LINE: if thisChar == '\n': sys.stdout.write("\n") state = SOURCE if not options.stripLine: sys.stdout.write(thisChar) elif state == COMMENT_CSTYLE: if not options.stripCStyle: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE elif state == COMMENT_JAVADOC: if not options.stripJavadoc: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE elif state == COMMENT_HEADERDOC: if not options.stripHeaderDoc: sys.stdout.write(thisChar) if prevChar == '*' and thisChar == '/': state = SOURCE file.close()
Python
#!/opt/ActivePython-2.7/bin/python # Sequence Creation # Create a sequence comparision based on user input or file reading from Tkinter import * class Application(Frame): """ GUI application that creates based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label self.selection = StringVar() # self.selection.set(None) column = 0 self.entry_selection = ["Enter two strings" , "Enter two file names"] for part in self.entry_selection: Radiobutton(self, text = part, variable = self.selection, value = part ).grid(row = 0, column = column, sticky = W) column += 1 # create a label and text entry for input string S Label(self, text = "The first string S: " ).grid(row = 1, column = 0, sticky = W) self.StringS_ent = Entry(self) self.StringS_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for input string T Label(self, text = "The second string T:" ).grid(row = 2, column = 0, sticky = W) self.StringT_ent = Entry(self) self.StringT_ent.grid(row = 2, column = 1, sticky = W) # create labels and scrolling text entries for costs of deleting, inserting and substituting # characters, cdel, cins, csub Label(self, text = "weight of insertion cins:").grid(row = 3, column = 0, sticky = W) self.cins = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cins.grid(row = 3, column = 1, sticky = W) Label(self, text = "weight of deletion cdel:").grid(row = 4, column = 0, sticky = W) self.cdel = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cdel.grid(row = 4, column = 1, sticky = W) Label(self, text = "weight of substitution csub:").grid(row = 5, column = 0, sticky = W) self.csub = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.csub.grid(row = 5, column = 1, sticky = W) #create output preferences, use Checkbutton for multiple choices of distance matrix, backtrack #matrix, and alignment Label(self, text = "Please choose your preferred output contents:" ).grid(row = 6, column = 0, rowspan = 3, sticky = W) self.get_edit = BooleanVar() Checkbutton(self, text = "The full edit distance matrix", variable = self.get_edit, ).grid(row = 6, column = 1, sticky = W) self.get_back = BooleanVar() Checkbutton(self, text = "The backtrack matrix", variable = self.get_back, ).grid(row = 7, column = 1, sticky = W) self.get_alignment = BooleanVar() Checkbutton(self, text = "The alignment", variable = self.get_alignment, ).grid(row = 8, column = 1, sticky = W) # create a submit button Button(self, text = "Show output:", command = self.get_matrix ).grid(row = 9, column = 0, columnspan = 2, sticky = W) # create a scroll bar self.scrollbar = Scrollbar(self, orient = VERTICAL) self.scrollbar.grid(row = 0, column = 3, rowspan = 9, sticky = W + S + N + E) self.scrollbar1 = Scrollbar(self, orient = HORIZONTAL) self.scrollbar1.grid(row = 9, column = 2, sticky = W + S + N + E) self.font = ('courier',16) self.matrix_txt = Text(self, width = 30, height = 40, wrap = WORD, font = self.font, \ yscrollcommand = self.scrollbar.set, xscrollcommand = self.scrollbar1.set) self.matrix_txt.grid(row = 0, column = 2, rowspan = 9) self.scrollbar.config(command = self.matrix_txt.yview) self.scrollbar1.config(command = self.matrix_txt.xview) def get_matrix(self): """ Fill text box with new story based on user input. """ # get values from the GUI, use audiobutton for either input, two strings or two files self.String_S = self.StringS_ent.get() self.String_T = self.StringT_ent.get() print self.selection.get() if self.selection.get() == "Enter two strings": pass elif self.selection.get() == "Enter two file names": self.fp1 = open(self.String_S,"r") self.fp2 = open(self.String_T,"r") self.String_S = self.fp1.read() self.String_T = self.fp2.read() self.String_S = self.String_S[0: len(self.String_S)-1] self.String_T = self.String_T[0: len(self.String_T)-1] self.cins_value = self.cins.get() self.cdel_value = self.cdel.get() self.csub_value = self.csub.get() self.dist = {} self.backtrack = {} self.dist[(0 , 0)] = 0 self.backtrack[(0 , 0)] = 0 # calculate the values in edit distance matrix and obtain back track matrix according to dynamic programming for i in range (1 , len(self.String_S) + 1): self.dist[(i , 0)] = self.dist[(i-1 , 0)] + self.cdel_value self.backtrack[(i , 0)] = "|" for j in range (1, len(self.String_T) + 1): self.dist[(0 , j)] = self.dist[(0 , j-1)] + self.cins_value self.backtrack[(0 , j)] = "-" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 <= self.dist2 and self.dist1 <= self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 <= self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 < self.dist1 and self.dist3 < self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 < self.dist2 and self.dist1 < self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 < self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 <= self.dist1 and self.dist3 <= self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" self.print_matrix() # print distance matrix, back track matrix and alignment def print_matrix(self): distance = "" if self.get_edit.get() == 1: #if the checkbutton of edit distance matrix is pressed, calculate #values according to dynamic programming for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.dist[(i , j)], distance += str(self.dist[(i , j)]) distance += " " print "\n" distance += "\n" distance += "\n" if self.get_back.get() == 1: # if the checkbutton of back track matrix is pressed, trace back # the way to obtain minimal edit distance value for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.backtrack[(i , j)], distance += str(self.backtrack[(i , j)]) distance += " " print "\n" distance += "\n" distance += "\n" #get the alignment accroding to the charactor on path that optimal #value is obtained if self.get_alignment.get() == 1: m = 0 self.dict = {} i = len(self.String_S) j = len(self.String_T) while i >= 0 and j >= 0: if self.backtrack[(i , j)] == "|": self.dict[m] = "|" m += 1 i -= 1 continue elif self.backtrack[(i , j)] == "-": self.dict[m] = "-" m += 1 j -= 1 continue elif self.backtrack[(i , j)] == "\\": self.dict[m] = "\\" m += 1 i -= 1 j -= 1 continue else: self.dict[m] = "0" i -= 1 j -= 1 m += 1 # find corresponding character in alignment in strings according to path in back track matrix m = m - 1 i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "-": print "-", distance += "-" distance += " " j += 1 else: print self.String_S[m - i - j - 1], distance += str(self.String_S[m - i - j - 1]) distance += " " i -= 1 print "\n" distance += "\n" i = m - 1 j = 0 k = 0 while (i >= 0): if self.dict[i] == "\\": if self.String_T[m - i - j - 1] == self.String_S[m - i - k - 1]: print "|", distance += "|" distance += " " else: print " ", distance += " " distance += " " elif self.dict[i] == "|": j += 1 print " ", distance += " " distance += " " elif self.dict[i] == "-": k += 1 print " ", distance += " " distance += " " i -= 1 print "\n" distance += "\n" i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "|": print "-", distance += "-" distance += " " j += 1 else: print self.String_T[m - i - j - 1], distance += str(self.String_T[m - i - j - 1]) distance += " " i -= 1 print "\n" distance += "\n" distance += "\n" distance += "final edit distance value:" distance += " " distance += str(self.dist[len(self.String_S), len(self.String_T)]) distance += "\n" self.matrix_txt.insert(0.0 , distance) # main root = Tk() root.title("Sequence Compare") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # Sequence Creation # Create a sequence comparision based on user input or file reading from Tkinter import * class Application(Frame): """ GUI application that creates based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label self.selection = StringVar() # self.selection.set(None) column = 0 self.entry_selection = ["Enter two strings" , "Enter two file names"] for part in self.entry_selection: Radiobutton(self, text = part, variable = self.selection, value = part ).grid(row = 0, column = column, sticky = W) column += 1 # create a label and text entry for input string S Label(self, text = "The first string S: " ).grid(row = 1, column = 0, sticky = W) self.StringS_ent = Entry(self) self.StringS_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for input string T Label(self, text = "The second string T:" ).grid(row = 2, column = 0, sticky = W) self.StringT_ent = Entry(self) self.StringT_ent.grid(row = 2, column = 1, sticky = W) # create labels and scrolling text entries for costs of deleting, inserting and substituting # characters, cdel, cins, csub Label(self, text = "weight of insertion cins:").grid(row = 3, column = 0, sticky = W) self.cins = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cins.grid(row = 3, column = 1, sticky = W) Label(self, text = "weight of deletion cdel:").grid(row = 4, column = 0, sticky = W) self.cdel = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cdel.grid(row = 4, column = 1, sticky = W) Label(self, text = "weight of substitution csub:").grid(row = 5, column = 0, sticky = W) self.csub = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.csub.grid(row = 5, column = 1, sticky = W) #create output preferences, use Checkbutton for multiple choices of distance matrix, backtrack #matrix, and alignment Label(self, text = "Please choose your preferred output contents:" ).grid(row = 6, column = 0, rowspan = 3, sticky = W) self.get_edit = BooleanVar() Checkbutton(self, text = "The full edit distance matrix", variable = self.get_edit, ).grid(row = 6, column = 1, sticky = W) self.get_back = BooleanVar() Checkbutton(self, text = "The backtrack matrix", variable = self.get_back, ).grid(row = 7, column = 1, sticky = W) self.get_alignment = BooleanVar() Checkbutton(self, text = "The alignment", variable = self.get_alignment, ).grid(row = 8, column = 1, sticky = W) # create a submit button Button(self, text = "Show output:", command = self.get_matrix ).grid(row = 9, column = 0, columnspan = 2, sticky = W) # create a scroll bar self.scrollbar = Scrollbar(self, orient = VERTICAL) self.scrollbar.grid(row = 0, column = 3, rowspan = 9, sticky = W + S + N + E) self.scrollbar1 = Scrollbar(self, orient = HORIZONTAL) self.scrollbar1.grid(row = 9, column = 2, sticky = W + S + N + E) self.font = ('courier',16) self.matrix_txt = Text(self, width = 30, height = 40, wrap = WORD, font = self.font, \ yscrollcommand = self.scrollbar.set, xscrollcommand = self.scrollbar1.set) self.matrix_txt.grid(row = 0, column = 2, rowspan = 9) self.scrollbar.config(command = self.matrix_txt.yview) self.scrollbar1.config(command = self.matrix_txt.xview) def get_matrix(self): """ Fill text box with new story based on user input. """ # get values from the GUI, use audiobutton for either input, two strings or two files self.String_S = self.StringS_ent.get() self.String_T = self.StringT_ent.get() print self.selection.get() if self.selection.get() == "Enter two strings": pass elif self.selection.get() == "Enter two file names": self.fp1 = open(self.String_S,"r") self.fp2 = open(self.String_T,"r") self.String_S = self.fp1.read() self.String_T = self.fp2.read() self.String_S = self.String_S[0: len(self.String_S)-1] self.String_T = self.String_T[0: len(self.String_T)-1] self.cins_value = self.cins.get() self.cdel_value = self.cdel.get() self.csub_value = self.csub.get() self.dist = {} self.backtrack = {} self.dist[(0 , 0)] = 0 self.backtrack[(0 , 0)] = 0 # calculate the values in edit distance matrix and obtain back track matrix according to dynamic programming for i in range (1 , len(self.String_S) + 1): self.dist[(i , 0)] = self.dist[(i-1 , 0)] + self.cdel_value self.backtrack[(i , 0)] = "|" for j in range (1, len(self.String_T) + 1): self.dist[(0 , j)] = self.dist[(0 , j-1)] + self.cins_value self.backtrack[(0 , j)] = "-" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 <= self.dist2 and self.dist1 <= self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 <= self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 < self.dist1 and self.dist3 < self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 < self.dist2 and self.dist1 < self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 < self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 <= self.dist1 and self.dist3 <= self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" self.print_matrix() # print distance matrix, back track matrix and alignment def print_matrix(self): distance = "" if self.get_edit.get() == 1: #if the checkbutton of edit distance matrix is pressed, calculate #values according to dynamic programming for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.dist[(i , j)], distance += str(self.dist[(i , j)]) distance += " " print "\n" distance += "\n" distance += "\n" if self.get_back.get() == 1: # if the checkbutton of back track matrix is pressed, trace back # the way to obtain minimal edit distance value for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.backtrack[(i , j)], distance += str(self.backtrack[(i , j)]) distance += " " print "\n" distance += "\n" distance += "\n" #get the alignment accroding to the charactor on path that optimal #value is obtained if self.get_alignment.get() == 1: m = 0 self.dict = {} i = len(self.String_S) j = len(self.String_T) while i >= 0 and j >= 0: if self.backtrack[(i , j)] == "|": self.dict[m] = "|" m += 1 i -= 1 continue elif self.backtrack[(i , j)] == "-": self.dict[m] = "-" m += 1 j -= 1 continue elif self.backtrack[(i , j)] == "\\": self.dict[m] = "\\" m += 1 i -= 1 j -= 1 continue else: self.dict[m] = "0" i -= 1 j -= 1 m += 1 # find corresponding character in alignment in strings according to path in back track matrix m = m - 1 i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "-": print "-", distance += "-" distance += " " j += 1 else: print self.String_S[m - i - j - 1], distance += str(self.String_S[m - i - j - 1]) distance += " " i -= 1 print "\n" distance += "\n" i = m - 1 j = 0 k = 0 while (i >= 0): if self.dict[i] == "\\": if self.String_T[m - i - j - 1] == self.String_S[m - i - k - 1]: print "|", distance += "|" distance += " " else: print " ", distance += " " distance += " " elif self.dict[i] == "|": j += 1 print " ", distance += " " distance += " " elif self.dict[i] == "-": k += 1 print " ", distance += " " distance += " " i -= 1 print "\n" distance += "\n" i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "|": print "-", distance += "-" distance += " " j += 1 else: print self.String_T[m - i - j - 1], distance += str(self.String_T[m - i - j - 1]) distance += " " i -= 1 print "\n" distance += "\n" distance += "\n" distance += "final edit distance value:" distance += " " distance += str(self.dist[len(self.String_S), len(self.String_T)]) distance += "\n" self.matrix_txt.insert(0.0 , distance) # main root = Tk() root.title("Sequence Compare") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # movie_chooser.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Choose your favorite movie types" ).grid(row = 0, column = 0, sticky = W) # create Comedy check button self.likes_comedy = BooleanVar() Checkbutton(self, text = "Comedy", variable = self.likes_comedy, command = self.update_text ).grid(row = 2, column = 0, sticky = W) # create Drama check button self.likes_drama = BooleanVar() Checkbutton(self, text = "Drama", variable = self.likes_drama, command = self.update_text ).grid(row = 3, column = 0, sticky = W) # create Romance check button self.likes_romance = BooleanVar() Checkbutton(self, text = "Romance", variable = self.likes_romance, command = self.update_text ).grid(row = 4, column = 0, sticky = W) # create text field to display results self.results_txt = Text(self, width = 40, height = 5, wrap = WORD) self.results_txt.grid(row = 5, column = 0, columnspan = 3) def update_text(self): likes = "" if self.likes_comedy.get(): likes += "You like comedic movies.\n" if self.likes_drama.get(): likes += "You like dramatic movies.\n" if self.likes_romance.get(): likes += "You like romantic movies." self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, likes) root = Tk() root.title("Movie Chooser") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # longevity.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): # create label for instructions self.inst_lbl = Label(self, text = "Enter password for \ the secret of longevity") self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) # create label for password self.pw_lbl = Label(self, text = "Password: ") self.pw_lbl.grid(row = 1, column = 0, sticky = W) # create entry widget to accept password self.pw_ent = Entry(self) self.pw_ent.grid(row = 1, column = 1, sticky = W) # create submit button self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row = 2, column = 0, sticky = W) # create text widget to display message self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W) def reveal(self): """ Display message based on password. """ contents = self.pw_ent.get() if contents == "secret": message = "Here's the secret to living to 100: \ live to 99 and then be VERY careful." else: message = "That's not the correct password, \ so I can't share the secret with you." self.secret_txt.delete(0.0, END) self.secret_txt.insert(0.0, message) root = Tk() root.title("Longevity") # root.geometry("270x170") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # Mad Lib # Create a story based on user input from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text = "Enter information for a new story" ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label and text entry for the name of a person Label(self, text = "Person: " ).grid(row = 1, column = 0, sticky = W) self.person_ent = Entry(self) self.person_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for a plural noun Label(self, text = "Plural Noun:" ).grid(row = 2, column = 0, sticky = W) self.noun_ent = Entry(self) self.noun_ent.grid(row = 2, column = 1, sticky = W) # create a label and text entry for a verb Label(self, text = "Verb:" ).grid(row = 3, column = 0, sticky = W) self.verb_ent = Entry(self) self.verb_ent.grid(row = 3, column = 1, sticky = W) # create a label for adjectives check buttons Label(self, text = "Adjective(s):" ).grid(row = 4, column = 0, sticky = W) # create itchy check button self.is_itchy = BooleanVar() Checkbutton(self, text = "itchy", variable = self.is_itchy ).grid(row = 4, column = 1, sticky = W) # create joyous check button self.is_joyous = BooleanVar() Checkbutton(self, text = "joyous", variable = self.is_joyous ).grid(row = 4, column = 2, sticky = W) # create electric check button self.is_electric = BooleanVar() Checkbutton(self, text = "electric", variable = self.is_electric ).grid(row = 4, column = 3, sticky = W) # create a label for body parts radio buttons Label(self, text = "Body Part:" ).grid(row = 5, column = 0, sticky = W) # create variable for single, body part self.body_part = StringVar() self.body_part.set(None) # create body part radio buttons body_parts = ["bellybutton", "big toe", "medulla oblongata"] column = 1 for part in body_parts: Radiobutton(self, text = part, variable = self.body_part, value = part ).grid(row = 5, column = column, sticky = W) column += 1 # create a submit button Button(self, text = "Click for story", command = self.tell_story ).grid(row = 6, column = 0, sticky = W) self.story_txt = Text(self, width = 75, height = 10, wrap = WORD) self.story_txt.grid(row = 7, column = 0, columnspan = 4) def tell_story(self): """ Fill text box with new story based on user input. """ # get values from the GUI person = self.person_ent.get() noun = self.noun_ent.get() verb = self.verb_ent.get() adjectives = "" if self.is_itchy.get(): adjectives += "itchy, " if self.is_joyous.get(): adjectives += "joyous, " if self.is_electric.get(): adjectives += "electric, " body_part = self.body_part.get() # create the story story = "The famous explorer " story += person story += " had nearly given up a life-long quest to find The Lost City of " story += noun.title() story += " when one day, the " story += noun story += " found " story += person + ". " story += "A strong, " story += adjectives story += "peculiar feeling overwhelmed the explorer. " story += "After all this time, the quest was finally over. A tear came to " story += person + "'s " story += body_part + ". " story += "And then, the " story += noun story += " promptly devoured " story += person + ". " story += "The moral of the story? Be careful what you " story += verb story += " for." # display the story self.story_txt.delete(0.0, END) self.story_txt.insert(0.0, story) # main root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # labeler.py from Tkinter import * root = Tk() root.title("Labeler") # root.geometry("200x100") app = Frame(root) app.grid() lbl = Label(app, text = "I'm a label!") lbl.grid() root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # movie_chooser2.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Choose your favorite movie types" ).grid(row = 0, column = 0, sticky = W) # create variable for single, favorite type self.favorite = StringVar() # create Comedy radio button Radiobutton(self, text = "Comedy", variable = self.favorite, value = "comedy.", command = self.update_text ).grid(row = 2, column = 0, sticky = W) # create Drama radio button Radiobutton(self, text = "Drama", variable = self.favorite, value = "drama.", command = self.update_text ).grid(row = 3, column = 0, sticky = W) # create Romance radio button Radiobutton(self, text = "Romance", variable = self.favorite, value = "romance.", command = self.update_text ).grid(row = 4, column = 0, sticky = W) # create text field to display results self.results_txt = Text(self, width = 40, height = 5, wrap = WORD) self.results_txt.grid(row = 5, column = 0, columnspan = 3) def update_text(self): """ Update text area and display user's favorite movie type. """ message = "Your favorite type of movie is " message += self.favorite.get() self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, message) root = Tk() root.title("Movie Chooser 2") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # longevity.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): # create label for instructions self.inst_lbl = Label(self, text = "Enter password for \ the secret of longevity") self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) # create label for password self.pw_lbl = Label(self, text = "Password: ") self.pw_lbl.grid(row = 1, column = 0, sticky = W) # create entry widget to accept password self.pw_ent = Entry(self) self.pw_ent.grid(row = 1, column = 1, sticky = W) # create submit button self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row = 2, column = 0, sticky = W) # create text widget to display message self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W) def reveal(self): """ Display message based on password. """ contents = self.pw_ent.get() if contents == "secret": message = "Here's the secret to living to 100: \ live to 99 and then be VERY careful." else: message = "That's not the correct password, \ so I can't share the secret with you." self.secret_txt.delete(0.0, END) self.secret_txt.insert(0.0, message) root = Tk() root.title("Longevity") # root.geometry("270x170") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # Mad Lib # Create a story based on user input from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text = "Enter information for a new story" ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label and text entry for the name of a person Label(self, text = "Person: " ).grid(row = 1, column = 0, sticky = W) self.person_ent = Entry(self) self.person_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for a plural noun Label(self, text = "Plural Noun:" ).grid(row = 2, column = 0, sticky = W) self.noun_ent = Entry(self) self.noun_ent.grid(row = 2, column = 1, sticky = W) # create a label and text entry for a verb Label(self, text = "Verb:" ).grid(row = 3, column = 0, sticky = W) self.verb_ent = Entry(self) self.verb_ent.grid(row = 3, column = 1, sticky = W) # create a label for adjectives check buttons Label(self, text = "Adjective(s):" ).grid(row = 4, column = 0, sticky = W) # create itchy check button self.is_itchy = BooleanVar() Checkbutton(self, text = "itchy", variable = self.is_itchy ).grid(row = 4, column = 1, sticky = W) # create joyous check button self.is_joyous = BooleanVar() Checkbutton(self, text = "joyous", variable = self.is_joyous ).grid(row = 4, column = 2, sticky = W) # create electric check button self.is_electric = BooleanVar() Checkbutton(self, text = "electric", variable = self.is_electric ).grid(row = 4, column = 3, sticky = W) # create a label for body parts radio buttons Label(self, text = "Body Part:" ).grid(row = 5, column = 0, sticky = W) # create variable for single, body part self.body_part = StringVar() self.body_part.set(None) # create body part radio buttons body_parts = ["bellybutton", "big toe", "medulla oblongata"] column = 1 for part in body_parts: Radiobutton(self, text = part, variable = self.body_part, value = part ).grid(row = 5, column = column, sticky = W) column += 1 # create a submit button Button(self, text = "Click for story", command = self.tell_story ).grid(row = 6, column = 0, sticky = W) self.story_txt = Text(self, width = 75, height = 10, wrap = WORD) self.story_txt.grid(row = 7, column = 0, columnspan = 4) def tell_story(self): """ Fill text box with new story based on user input. """ # get values from the GUI person = self.person_ent.get() noun = self.noun_ent.get() verb = self.verb_ent.get() adjectives = "" if self.is_itchy.get(): adjectives += "itchy, " if self.is_joyous.get(): adjectives += "joyous, " if self.is_electric.get(): adjectives += "electric, " body_part = self.body_part.get() # create the story story = "The famous explorer " story += person story += " had nearly given up a life-long quest to find The Lost City of " story += noun.title() story += " when one day, the " story += noun story += " found " story += person + ". " story += "A strong, " story += adjectives story += "peculiar feeling overwhelmed the explorer. " story += "After all this time, the quest was finally over. A tear came to " story += person + "'s " story += body_part + ". " story += "And then, the " story += noun story += " promptly devoured " story += person + ". " story += "The moral of the story? Be careful what you " story += verb story += " for." # display the story self.story_txt.delete(0.0, END) self.story_txt.insert(0.0, story) # main root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # lazy_buttons2.py from Tkinter import * class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): self.bttn1 = Button(self, text = "I do nothing!") self.bttn1.grid() self.bttn2 = Button(self) self.bttn2.grid() self.bttn2.configure(text = "Me too!") self.bttn3 = Button(self) self.bttn3.grid() self.bttn3["text"] = "Same here!" # main root = Tk() root.title("Lazy Buttons 2") root.geometry("200x85") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # lazy_buttons.py from Tkinter import * root = Tk() root.title("Lazy Buttons") root.geometry("200x100") app = Frame(root) app.grid() bttn1 = Button(app, text = "I do nothing!") bttn1.grid() bttn2 = Button(app) bttn2.grid() bttn2.configure(text = "Me too!") bttn3 = Button(app) bttn3.grid() bttn3["text"] = "Same here!" root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # movie_chooser.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Choose your favorite movie types" ).grid(row = 0, column = 0, sticky = W) # create Comedy check button self.likes_comedy = BooleanVar() Checkbutton(self, text = "Comedy", variable = self.likes_comedy, command = self.update_text ).grid(row = 2, column = 0, sticky = W) # create Drama check button self.likes_drama = BooleanVar() Checkbutton(self, text = "Drama", variable = self.likes_drama, command = self.update_text ).grid(row = 3, column = 0, sticky = W) # create Romance check button self.likes_romance = BooleanVar() Checkbutton(self, text = "Romance", variable = self.likes_romance, command = self.update_text ).grid(row = 4, column = 0, sticky = W) # create text field to display results self.results_txt = Text(self, width = 40, height = 5, wrap = WORD) self.results_txt.grid(row = 5, column = 0, columnspan = 3) def update_text(self): likes = "" if self.likes_comedy.get(): likes += "You like comedic movies.\n" if self.likes_drama.get(): likes += "You like dramatic movies.\n" if self.likes_romance.get(): likes += "You like romantic movies." self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, likes) root = Tk() root.title("Movie Chooser") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # click_counter.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.bttn_clicks = 0 # number clicks self.create_widget() def create_widget(self): self.bttn = Button(self) self.bttn["text"]= "Total Clicks: 0" self.bttn["command"] = self.update_count self.bttn.grid() def update_count(self): self.bttn_clicks += 1 self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks) # main root = Tk() root.title("Click Counter") root.geometry("200x85") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # Mad Lib # Create a story based on user input from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text = "Enter information for a new story" ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label and text entry for input string S Label(self, text = "The first string S: " ).grid(row = 1, column = 0, sticky = W) self.StringS_ent = Entry(self) self.StringS_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for input string T Label(self, text = "The second string T:" ).grid(row = 2, column = 0, sticky = W) self.StringT_ent = Entry(self) self.StringT_ent.grid(row = 2, column = 1, sticky = W) Label(self, text = "weight of insertion cins:").grid(row = 11, column = 0, sticky = W) self.cins = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cins.grid(row = 11, column = 1) Label(self, text = "weight of deletion cdel:").grid(row = 12, column = 0, sticky = W) self.cdel = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cdel.grid(row = 12, column = 1) Label(self, text = "weight of substitution csub:").grid(row = 13, column = 0, sticky = W) self.csub = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.csub.grid(row = 13, column = 1) # cin.pack(row = 5, column = 1, sticky = W) # cdel = Scale(master, from_ = 0, to = 20, orient = HORIZONTAL) # cdel.pack() # csub = Scale(master, from_ = 0, to = 20, orient = HORIZONTAL) # csub.pack() # print cin.get() # create electric check button # self.is_electric = BooleanVar() # Checkbutton(self, # text = "electric", # variable = self.is_electric # ).grid(row = 4, column = 3, sticky = W) # create a label for body parts radio buttons Label(self, text = "Please choose your preferred output contents:" ).grid(row = 5, column = 0, sticky = W) # create variable for single, body part self.get_edit = BooleanVar() Checkbutton(self, text = "The full edit distance matrix", variable = self.get_edit, # command = self.updata_text ).grid(row = 5, column = 1, sticky = W) # column = 2 self.get_back = BooleanVar() Checkbutton(self, text = "The backtrack matrix", variable = self.get_back, # command = self.updata_text ).grid(row = 5, column = 2, sticky = W) # column = 3 self.get_alignment = BooleanVar() Checkbutton(self, text = "The alignment", variable = self.get_alignment, # command = self.updata_text ).grid(row = 5, column = 3, sticky = W) # create a submit button Button(self, text = "Show output:", command = self.get_matrix ).grid(row = 6, column = 0, sticky = W) self.story_txt = Text(self, width = 75, height = 10, wrap = WORD) self.story_txt.grid(row = 7, column = 0, columnspan = 4) def get_matrix(self): """ Fill text box with new story based on user input. """ # get values from the GUI self.String_S = self.StringS_ent.get() self.String_T = self.StringT_ent.get() self.cins_value = self.cins.get() self.cdel_value = self.cdel.get() self.csub_value = self.csub.get() self.dist = {} self.backtrack = {} self.dist[(0 , 0)] = 0 self.backtrack[(0 , 0)] = 0 for i in range (1 , len(self.String_S) + 1): self.dist[(i , 0)] = self.dist[(i-1 , 0)] + self.cdel_value self.backtrack[(i , 0)] = "|" for j in range (1, len(self.String_T) + 1): self.dist[(0 , j)] = self.dist[(0 , j-1)] + self.cins_value self.backtrack[(0 , j)] = "-" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 <= self.dist2 and self.dist1 <= self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 <= self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 < self.dist1 and self.dist3 < self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 < self.dist2 and self.dist1 < self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 < self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 <= self.dist1 and self.dist3 <= self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" self.print_matrix() def print_matrix(self): if self.get_edit.get() == 1: for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.dist[(i , j)], print "\n" if self.get_back.get() == 1: for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.backtrack[(i , j)], print "\n" if self.get_alignment.get() == 1: m = 0 self.dict = {} i = len(self.String_S) j = len(self.String_T) while i >= 0 and j >= 0: if self.backtrack[(i , j)] == "|": self.dict[m] = "|" m += 1 i -= 1 continue elif self.backtrack[(i , j)] == "-": self.dict[m] = "-" m += 1 j -= 1 continue elif self.backtrack[(i , j)] == "\\": self.dict[m] = "\\" m += 1 i -= 1 j -= 1 continue else: self.dict[m] = "0" i -= 1 j -= 1 m += 1 m = m - 1 i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "-": print "-", j += 1 else: print self.String_S[m - i - j - 1], i -= 1 print "\n" i = m - 1 j = 0 k = 0 while (i >= 0): if self.dict[i] == "\\": if self.String_T[m - i - j - 1] == self.String_S[m - i - k - 1]: print "|", else: print " ", elif self.dict[i] == "|": j += 1 print " ", elif self.dict[i] == "-": k += 1 print " ", i -= 1 print "\n" i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "|": print "-", j += 1 else: print self.String_T[m - i - j - 1], i -= 1 print "\n" # main root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # simple_gui.py from Tkinter import * root = Tk() root.title("Simple GUI") root.geometry("200x100") root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # movie_chooser2.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Choose your favorite movie types" ).grid(row = 0, column = 0, sticky = W) # create variable for single, favorite type self.favorite = StringVar() # create Comedy radio button Radiobutton(self, text = "Comedy", variable = self.favorite, value = "comedy.", command = self.update_text ).grid(row = 2, column = 0, sticky = W) # create Drama radio button Radiobutton(self, text = "Drama", variable = self.favorite, value = "drama.", command = self.update_text ).grid(row = 3, column = 0, sticky = W) # create Romance radio button Radiobutton(self, text = "Romance", variable = self.favorite, value = "romance.", command = self.update_text ).grid(row = 4, column = 0, sticky = W) # create text field to display results self.results_txt = Text(self, width = 40, height = 5, wrap = WORD) self.results_txt.grid(row = 5, column = 0, columnspan = 3) def update_text(self): """ Update text area and display user's favorite movie type. """ message = "Your favorite type of movie is " message += self.favorite.get() self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, message) root = Tk() root.title("Movie Chooser 2") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # labeler.py from Tkinter import * root = Tk() root.title("Labeler") # root.geometry("200x100") app = Frame(root) app.grid() lbl = Label(app, text = "I'm a label!") lbl.grid() root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # Mad Lib # Create a story based on user input from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text = "Enter information for a new story" ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label and text entry for input string S Label(self, text = "The first string S: " ).grid(row = 1, column = 0, sticky = W) self.StringS_ent = Entry(self) self.StringS_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for input string T Label(self, text = "The second string T:" ).grid(row = 2, column = 0, sticky = W) self.StringT_ent = Entry(self) self.StringT_ent.grid(row = 2, column = 1, sticky = W) Label(self, text = "weight of insertion cins:").grid(row = 11, column = 0, sticky = W) self.cins = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cins.grid(row = 11, column = 1) Label(self, text = "weight of deletion cdel:").grid(row = 12, column = 0, sticky = W) self.cdel = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.cdel.grid(row = 12, column = 1) Label(self, text = "weight of substitution csub:").grid(row = 13, column = 0, sticky = W) self.csub = Scale(self, from_ = 1, to = 20, orient = HORIZONTAL) self.csub.grid(row = 13, column = 1) # cin.pack(row = 5, column = 1, sticky = W) # cdel = Scale(master, from_ = 0, to = 20, orient = HORIZONTAL) # cdel.pack() # csub = Scale(master, from_ = 0, to = 20, orient = HORIZONTAL) # csub.pack() # print cin.get() # create electric check button # self.is_electric = BooleanVar() # Checkbutton(self, # text = "electric", # variable = self.is_electric # ).grid(row = 4, column = 3, sticky = W) # create a label for body parts radio buttons Label(self, text = "Please choose your preferred output contents:" ).grid(row = 5, column = 0, sticky = W) # create variable for single, body part self.get_edit = BooleanVar() Checkbutton(self, text = "The full edit distance matrix", variable = self.get_edit, # command = self.updata_text ).grid(row = 5, column = 1, sticky = W) # column = 2 self.get_back = BooleanVar() Checkbutton(self, text = "The backtrack matrix", variable = self.get_back, # command = self.updata_text ).grid(row = 5, column = 2, sticky = W) # column = 3 self.get_alignment = BooleanVar() Checkbutton(self, text = "The alignment", variable = self.get_alignment, # command = self.updata_text ).grid(row = 5, column = 3, sticky = W) # create a submit button Button(self, text = "Show output:", command = self.get_matrix ).grid(row = 6, column = 0, sticky = W) self.story_txt = Text(self, width = 75, height = 10, wrap = WORD) self.story_txt.grid(row = 7, column = 0, columnspan = 4) def get_matrix(self): """ Fill text box with new story based on user input. """ # get values from the GUI self.String_S = self.StringS_ent.get() self.String_T = self.StringT_ent.get() self.cins_value = self.cins.get() self.cdel_value = self.cdel.get() self.csub_value = self.csub.get() self.dist = {} self.backtrack = {} self.dist[(0 , 0)] = 0 self.backtrack[(0 , 0)] = 0 for i in range (1 , len(self.String_S) + 1): self.dist[(i , 0)] = self.dist[(i-1 , 0)] + self.cdel_value self.backtrack[(i , 0)] = "|" for j in range (1, len(self.String_T) + 1): self.dist[(0 , j)] = self.dist[(0 , j-1)] + self.cins_value self.backtrack[(0 , j)] = "-" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 <= self.dist2 and self.dist1 <= self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 <= self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 < self.dist1 and self.dist3 < self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" for i in range (1 , len(self.String_S) + 1): for j in range (1 , len(self.String_T) + 1): self.dist1 = self.dist[(i - 1 , j)] + self.cdel_value self.dist2 = self.dist[(i , j - 1)] + self.cins_value if self.String_T[j - 1] != self.String_S[i - 1]: self.dist3 = self.dist[(i - 1, j - 1)] + self.csub_value else: self.dist3 = self.dist[(i - 1, j - 1)] if self.dist1 < self.dist2 and self.dist1 < self.dist3: self.dist[(i , j)] = self.dist1 self.backtrack[(i , j)] = "|" elif self.dist2 < self.dist1 and self.dist2 < self.dist3: self.dist[(i , j)] = self.dist2 self.backtrack[(i , j)] = "-" elif self.dist3 <= self.dist1 and self.dist3 <= self.dist2: self.dist[(i , j)] = self.dist3 self.backtrack[(i , j)] = "\\" self.print_matrix() def print_matrix(self): if self.get_edit.get() == 1: for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.dist[(i , j)], print "\n" if self.get_back.get() == 1: for i in range (0 , len(self.String_S) + 1): for j in range (0 , len(self.String_T) + 1): print self.backtrack[(i , j)], print "\n" if self.get_alignment.get() == 1: m = 0 self.dict = {} i = len(self.String_S) j = len(self.String_T) while i >= 0 and j >= 0: if self.backtrack[(i , j)] == "|": self.dict[m] = "|" m += 1 i -= 1 continue elif self.backtrack[(i , j)] == "-": self.dict[m] = "-" m += 1 j -= 1 continue elif self.backtrack[(i , j)] == "\\": self.dict[m] = "\\" m += 1 i -= 1 j -= 1 continue else: self.dict[m] = "0" i -= 1 j -= 1 m += 1 m = m - 1 i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "-": print "-", j += 1 else: print self.String_S[m - i - j - 1], i -= 1 print "\n" i = m - 1 j = 0 k = 0 while (i >= 0): if self.dict[i] == "\\": if self.String_T[m - i - j - 1] == self.String_S[m - i - k - 1]: print "|", else: print " ", elif self.dict[i] == "|": j += 1 print " ", elif self.dict[i] == "-": k += 1 print " ", i -= 1 print "\n" i = m - 1 j = 0 while (i >= 0): if self.dict[i] == "|": print "-", j += 1 else: print self.String_T[m - i - j - 1], i -= 1 print "\n" # main root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # simple_gui.py from Tkinter import * root = Tk() root.title("Simple GUI") root.geometry("200x100") root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # lazy_buttons2.py from Tkinter import * class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): self.bttn1 = Button(self, text = "I do nothing!") self.bttn1.grid() self.bttn2 = Button(self) self.bttn2.grid() self.bttn2.configure(text = "Me too!") self.bttn3 = Button(self) self.bttn3.grid() self.bttn3["text"] = "Same here!" # main root = Tk() root.title("Lazy Buttons 2") root.geometry("200x85") app = Application(root) root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # lazy_buttons.py from Tkinter import * root = Tk() root.title("Lazy Buttons") root.geometry("200x100") app = Frame(root) app.grid() bttn1 = Button(app, text = "I do nothing!") bttn1.grid() bttn2 = Button(app) bttn2.grid() bttn2.configure(text = "Me too!") bttn3 = Button(app) bttn3.grid() bttn3["text"] = "Same here!" root.mainloop()
Python
#!/opt/ActivePython-2.7/bin/python # click_counter.py from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.bttn_clicks = 0 # number clicks self.create_widget() def create_widget(self): self.bttn = Button(self) self.bttn["text"]= "Total Clicks: 0" self.bttn["command"] = self.update_count self.bttn.grid() def update_count(self): self.bttn_clicks += 1 self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks) # main root = Tk() root.title("Click Counter") root.geometry("200x85") app = Application(root) root.mainloop()
Python
# graphics.py """Simple object oriented graphics library The library is designed to make it very easy for novice programmers to experiment with computer graphics in an object oriented fashion. It is written by John Zelle for use with the book "Python Programming: An Introduction to Computer Science" (Franklin, Beedle & Associates). LICENSE: This is open-source software released under the terms of the GPL (http://www.gnu.org/licenses/gpl.html). PLATFORMS: The package is a wrapper around Tkinter and should run on any platform where Tkinter is available. INSTALLATION: Put this file somewhere where Python can see it. OVERVIEW: There are two kinds of objects in the library. The GraphWin class implements a window where drawing can be done and various GraphicsObjects are provided that can be drawn into a GraphWin. As a simple example, here is a complete program to draw a circle of radius 10 centered in a 100x100 window: -------------------------------------------------------------------- from graphics import * def main(): win = GraphWin("My Circle", 100, 100) c = Circle(Point(50,50), 10) c.draw(win) win.getMouse() # Pause to view result win.close() # Close window when done main() -------------------------------------------------------------------- GraphWin objects support coordinate transformation through the setCoords method and pointer-based input through getMouse. The library provides the following graphical objects: Point Line Circle Oval Rectangle Polygon Text Entry (for text-based input) Image Various attributes of graphical objects can be set such as outline-color, fill-color and line-width. Graphical objects also support moving and hiding for animation effects. The library also provides a very simple class for pixel-based image manipulation, Pixmap. A pixmap can be loaded from a file and displayed using an Image object. Both getPixel and setPixel methods are provided for manipulating the image. DOCUMENTATION: For complete documentation, see Chapter 4 of "Python Programming: An Introduction to Computer Science" by John Zelle, published by Franklin, Beedle & Associates. Also see http://mcsp.wartburg.edu/zelle/python for a quick reference""" # Version 4.2 5/26/2011 # * Modified Image to allow multiple undraws like other GraphicsObjects # Version 4.1 12/29/2009 # * Merged Pixmap and Image class. Old Pixmap removed, use Image. # Version 4.0.1 10/08/2009 # * Modified the autoflush on GraphWin to default to True # * Autoflush check on close, setBackground # * Fixed getMouse to flush pending clicks at entry # Version 4.0 08/2009 # * Reverted to non-threaded version. The advantages (robustness, # efficiency, ability to use with other Tk code, etc.) outweigh # the disadvantage that interactive use with IDLE is slightly more # cumbersome. # * Modified to run in either Python 2.x or 3.x (same file). # * Added Image.getPixmap() # * Added update() -- stand alone function to cause any pending # graphics changes to display. # # Version 3.4 10/16/07 # Fixed GraphicsError to avoid "exploded" error messages. # Version 3.3 8/8/06 # Added checkMouse method to GraphWin # Version 3.2.3 # Fixed error in Polygon init spotted by Andrew Harrington # Fixed improper threading in Image constructor # Version 3.2.2 5/30/05 # Cleaned up handling of exceptions in Tk thread. The graphics package # now raises an exception if attempt is made to communicate with # a dead Tk thread. # Version 3.2.1 5/22/05 # Added shutdown function for tk thread to eliminate race-condition # error "chatter" when main thread terminates # Renamed various private globals with _ # Version 3.2 5/4/05 # Added Pixmap object for simple image manipulation. # Version 3.1 4/13/05 # Improved the Tk thread communication so that most Tk calls # do not have to wait for synchonization with the Tk thread. # (see _tkCall and _tkExec) # Version 3.0 12/30/04 # Implemented Tk event loop in separate thread. Should now work # interactively with IDLE. Undocumented autoflush feature is # no longer necessary. Its default is now False (off). It may # be removed in a future version. # Better handling of errors regarding operations on windows that # have been closed. # Addition of an isClosed method to GraphWindow class. # Version 2.2 8/26/04 # Fixed cloning bug reported by Joseph Oldham. # Now implements deep copy of config info. # Version 2.1 1/15/04 # Added autoflush option to GraphWin. When True (default) updates on # the window are done after each action. This makes some graphics # intensive programs sluggish. Turning off autoflush causes updates # to happen during idle periods or when flush is called. # Version 2.0 # Updated Documentation # Made Polygon accept a list of Points in constructor # Made all drawing functions call TK update for easier animations # and to make the overall package work better with # Python 2.3 and IDLE 1.0 under Windows (still some issues). # Removed vestigial turtle graphics. # Added ability to configure font for Entry objects (analogous to Text) # Added setTextColor for Text as an alias of setFill # Changed to class-style exceptions # Fixed cloning of Text objects # Version 1.6 # Fixed Entry so StringVar uses _root as master, solves weird # interaction with shell in Idle # Fixed bug in setCoords. X and Y coordinates can increase in # "non-intuitive" direction. # Tweaked wm_protocol so window is not resizable and kill box closes. # Version 1.5 # Fixed bug in Entry. Can now define entry before creating a # GraphWin. All GraphWins are now toplevel windows and share # a fixed root (called _root). # Version 1.4 # Fixed Garbage collection of Tkinter images bug. # Added ability to set text atttributes. # Added Entry boxes. import time, os, sys try: # import as appropriate for 2.x vs. 3.x import tkinter as tk except: import Tkinter as tk ########################################################################## # Module Exceptions class GraphicsError(Exception): """Generic error class for graphics module exceptions.""" pass OBJ_ALREADY_DRAWN = "Object currently drawn" UNSUPPORTED_METHOD = "Object doesn't support operation" BAD_OPTION = "Illegal option value" DEAD_THREAD = "Graphics thread quit unexpectedly" _root = tk.Tk() _root.withdraw() def update(): _root.update() ############################################################################ # Graphics classes start here class GraphWin(tk.Canvas): """A GraphWin is a toplevel window for displaying graphics.""" def __init__(self, title="Graphics Window", width=200, height=200, autoflush=True): master = tk.Toplevel(_root) master.protocol("WM_DELETE_WINDOW", self.close) tk.Canvas.__init__(self, master, width=width, height=height) self.master.title(title) self.pack() master.resizable(0,0) self.foreground = "black" self.items = [] self.mouseX = None self.mouseY = None self.bind("<Button-1>", self._onClick) self.height = height self.width = width self.autoflush = autoflush self._mouseCallback = None self.trans = None self.closed = False master.lift() if autoflush: _root.update() def __checkOpen(self): if self.closed: raise GraphicsError("window is closed") def setBackground(self, color): """Set background color of the window""" self.__checkOpen() self.config(bg=color) self.__autoflush() def setCoords(self, x1, y1, x2, y2): """Set coordinates of window to run from (x1,y1) in the lower-left corner to (x2,y2) in the upper-right corner.""" self.trans = Transform(self.width, self.height, x1, y1, x2, y2) def close(self): """Close the window""" if self.closed: return self.closed = True self.master.destroy() self.__autoflush() def isClosed(self): return self.closed def isOpen(self): return not self.closed def __autoflush(self): if self.autoflush: _root.update() def plot(self, x, y, color="black"): """Set pixel (x,y) to the given color""" self.__checkOpen() xs,ys = self.toScreen(x,y) self.create_line(xs,ys,xs+1,ys, fill=color) self.__autoflush() def plotPixel(self, x, y, color="black"): """Set pixel raw (independent of window coordinates) pixel (x,y) to color""" self.__checkOpen() self.create_line(x,y,x+1,y, fill=color) self.__autoflush() def flush(self): """Update drawing to the window""" self.__checkOpen() self.update_idletasks() def getMouse(self): """Wait for mouse click and return Point object representing the click""" self.update() # flush any prior clicks self.mouseX = None self.mouseY = None while self.mouseX == None or self.mouseY == None: self.update() if self.isClosed(): raise GraphicsError("getMouse in closed window") time.sleep(.1) # give up thread x,y = self.toWorld(self.mouseX, self.mouseY) self.mouseX = None self.mouseY = None return Point(x,y) def checkMouse(self): """Return last mouse click or None if mouse has not been clicked since last call""" if self.isClosed(): raise GraphicsError("checkMouse in closed window") self.update() if self.mouseX != None and self.mouseY != None: x,y = self.toWorld(self.mouseX, self.mouseY) self.mouseX = None self.mouseY = None return Point(x,y) else: return None def getHeight(self): """Return the height of the window""" return self.height def getWidth(self): """Return the width of the window""" return self.width def toScreen(self, x, y): trans = self.trans if trans: return self.trans.screen(x,y) else: return x,y def toWorld(self, x, y): trans = self.trans if trans: return self.trans.world(x,y) else: return x,y def setMouseHandler(self, func): self._mouseCallback = func def _onClick(self, e): self.mouseX = e.x self.mouseY = e.y if self._mouseCallback: self._mouseCallback(Point(e.x, e.y)) class Transform: """Internal class for 2-D coordinate transformations""" def __init__(self, w, h, xlow, ylow, xhigh, yhigh): # w, h are width and height of window # (xlow,ylow) coordinates of lower-left [raw (0,h-1)] # (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)] xspan = (xhigh-xlow) yspan = (yhigh-ylow) self.xbase = xlow self.ybase = yhigh self.xscale = xspan/float(w-1) self.yscale = yspan/float(h-1) def screen(self,x,y): # Returns x,y in screen (actually window) coordinates xs = (x-self.xbase) / self.xscale ys = (self.ybase-y) / self.yscale return int(xs+0.5),int(ys+0.5) def world(self,xs,ys): # Returns xs,ys in world coordinates x = xs*self.xscale + self.xbase y = self.ybase - ys*self.yscale return x,y # Default values for various item configuration options. Only a subset of # keys may be present in the configuration dictionary for a given item DEFAULT_CONFIG = {"fill":"", "outline":"black", "width":"1", "arrow":"none", "text":"", "justify":"center", "font": ("helvetica", 12, "normal")} class GraphicsObject: """Generic base class for all of the drawable objects""" # A subclass of GraphicsObject should override _draw and # and _move methods. def __init__(self, options): # options is a list of strings indicating which options are # legal for this object. # When an object is drawn, canvas is set to the GraphWin(canvas) # object where it is drawn and id is the TK identifier of the # drawn shape. self.canvas = None self.id = None # config is the dictionary of configuration options for the widget. config = {} for option in options: config[option] = DEFAULT_CONFIG[option] self.config = config def setFill(self, color): """Set interior color to color""" self._reconfig("fill", color) def setOutline(self, color): """Set outline color to color""" self._reconfig("outline", color) def setWidth(self, width): """Set line weight to width""" self._reconfig("width", width) def draw(self, graphwin): """Draw the object in graphwin, which should be a GraphWin object. A GraphicsObject may only be drawn into one window. Raises an error if attempt made to draw an object that is already visible.""" if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN) if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window") self.canvas = graphwin self.id = self._draw(graphwin, self.config) if graphwin.autoflush: _root.update() def undraw(self): """Undraw the object (i.e. hide it). Returns silently if the object is not currently drawn.""" if not self.canvas: return if not self.canvas.isClosed(): self.canvas.delete(self.id) if self.canvas.autoflush: _root.update() self.canvas = None self.id = None def move(self, dx, dy): """move object dx units in x direction and dy units in y direction""" self._move(dx,dy) canvas = self.canvas if canvas and not canvas.isClosed(): trans = canvas.trans if trans: x = dx/ trans.xscale y = -dy / trans.yscale else: x = dx y = dy self.canvas.move(self.id, x, y) if canvas.autoflush: _root.update() def _reconfig(self, option, setting): # Internal method for changing configuration of the object # Raises an error if the option does not exist in the config # dictionary for this object if option not in self.config: raise GraphicsError(UNSUPPORTED_METHOD) options = self.config options[option] = setting if self.canvas and not self.canvas.isClosed(): self.canvas.itemconfig(self.id, options) if self.canvas.autoflush: _root.update() def _draw(self, canvas, options): """draws appropriate figure on canvas with options provided Returns Tk id of item drawn""" pass # must override in subclass def _move(self, dx, dy): """updates internal state of object to move it dx,dy units""" pass # must override in subclass class Point(GraphicsObject): def __init__(self, x, y): GraphicsObject.__init__(self, ["outline", "fill"]) self.setFill = self.setOutline self.x = x self.y = y def _draw(self, canvas, options): x,y = canvas.toScreen(self.x,self.y) return canvas.create_rectangle(x,y,x+1,y+1,options) def _move(self, dx, dy): self.x = self.x + dx self.y = self.y + dy def clone(self): other = Point(self.x,self.y) other.config = self.config.copy() return other def getX(self): return self.x def getY(self): return self.y class _BBox(GraphicsObject): # Internal base class for objects represented by bounding box # (opposite corners) Line segment is a degenerate case. def __init__(self, p1, p2, options=["outline","width","fill"]): GraphicsObject.__init__(self, options) self.p1 = p1.clone() self.p2 = p2.clone() def _move(self, dx, dy): self.p1.x = self.p1.x + dx self.p1.y = self.p1.y + dy self.p2.x = self.p2.x + dx self.p2.y = self.p2.y + dy def getP1(self): return self.p1.clone() def getP2(self): return self.p2.clone() def getCenter(self): p1 = self.p1 p2 = self.p2 return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0) class Rectangle(_BBox): def __init__(self, p1, p2): _BBox.__init__(self, p1, p2) def _draw(self, canvas, options): p1 = self.p1 p2 = self.p2 x1,y1 = canvas.toScreen(p1.x,p1.y) x2,y2 = canvas.toScreen(p2.x,p2.y) return canvas.create_rectangle(x1,y1,x2,y2,options) def clone(self): other = Rectangle(self.p1, self.p2) other.config = self.config.copy() return other class Oval(_BBox): def __init__(self, p1, p2): _BBox.__init__(self, p1, p2) def clone(self): other = Oval(self.p1, self.p2) other.config = self.config.copy() return other def _draw(self, canvas, options): p1 = self.p1 p2 = self.p2 x1,y1 = canvas.toScreen(p1.x,p1.y) x2,y2 = canvas.toScreen(p2.x,p2.y) return canvas.create_oval(x1,y1,x2,y2,options) class Circle(Oval): def __init__(self, center, radius): p1 = Point(center.x-radius, center.y-radius) p2 = Point(center.x+radius, center.y+radius) Oval.__init__(self, p1, p2) self.radius = radius def clone(self): other = Circle(self.getCenter(), self.radius) other.config = self.config.copy() return other def getRadius(self): return self.radius class Line(_BBox): def __init__(self, p1, p2): _BBox.__init__(self, p1, p2, ["arrow","fill","width"]) self.setFill(DEFAULT_CONFIG['outline']) self.setOutline = self.setFill def clone(self): other = Line(self.p1, self.p2) other.config = self.config.copy() return other def _draw(self, canvas, options): p1 = self.p1 p2 = self.p2 x1,y1 = canvas.toScreen(p1.x,p1.y) x2,y2 = canvas.toScreen(p2.x,p2.y) return canvas.create_line(x1,y1,x2,y2,options) def setArrow(self, option): if not option in ["first","last","both","none"]: raise GraphicsError(BAD_OPTION) self._reconfig("arrow", option) class Polygon(GraphicsObject): def __init__(self, *points): # if points passed as a list, extract it if len(points) == 1 and type(points[0]) == type([]): points = points[0] self.points = list(map(Point.clone, points)) GraphicsObject.__init__(self, ["outline", "width", "fill"]) def clone(self): other = Polygon(*self.points) other.config = self.config.copy() return other def getPoints(self): return list(map(Point.clone, self.points)) def _move(self, dx, dy): for p in self.points: p.move(dx,dy) def _draw(self, canvas, options): args = [canvas] for p in self.points: x,y = canvas.toScreen(p.x,p.y) args.append(x) args.append(y) args.append(options) return GraphWin.create_polygon(*args) class Text(GraphicsObject): def __init__(self, p, text): GraphicsObject.__init__(self, ["justify","fill","text","font"]) self.setText(text) self.anchor = p.clone() self.setFill(DEFAULT_CONFIG['outline']) self.setOutline = self.setFill def _draw(self, canvas, options): p = self.anchor x,y = canvas.toScreen(p.x,p.y) return canvas.create_text(x,y,options) def _move(self, dx, dy): self.anchor.move(dx,dy) def clone(self): other = Text(self.anchor, self.config['text']) other.config = self.config.copy() return other def setText(self,text): self._reconfig("text", text) def getText(self): return self.config["text"] def getAnchor(self): return self.anchor.clone() def setFace(self, face): if face in ['helvetica','arial','courier','times roman']: f,s,b = self.config['font'] self._reconfig("font",(face,s,b)) else: raise GraphicsError(BAD_OPTION) def setSize(self, size): if 5 <= size <= 36: f,s,b = self.config['font'] self._reconfig("font", (f,size,b)) else: raise GraphicsError(BAD_OPTION) def setStyle(self, style): if style in ['bold','normal','italic', 'bold italic']: f,s,b = self.config['font'] self._reconfig("font", (f,s,style)) else: raise GraphicsError(BAD_OPTION) def setTextColor(self, color): self.setFill(color) class Entry(GraphicsObject): def __init__(self, p, width): GraphicsObject.__init__(self, []) self.anchor = p.clone() #print self.anchor self.width = width self.text = tk.StringVar(_root) self.text.set("") self.fill = "gray" self.color = "black" self.font = DEFAULT_CONFIG['font'] self.entry = None def _draw(self, canvas, options): p = self.anchor x,y = canvas.toScreen(p.x,p.y) frm = tk.Frame(canvas.master) self.entry = tk.Entry(frm, width=self.width, textvariable=self.text, bg = self.fill, fg = self.color, font=self.font) self.entry.pack() #self.setFill(self.fill) return canvas.create_window(x,y,window=frm) def getText(self): return self.text.get() def _move(self, dx, dy): self.anchor.move(dx,dy) def getAnchor(self): return self.anchor.clone() def clone(self): other = Entry(self.anchor, self.width) other.config = self.config.copy() other.text = tk.StringVar() other.text.set(self.text.get()) other.fill = self.fill return other def setText(self, t): self.text.set(t) def setFill(self, color): self.fill = color if self.entry: self.entry.config(bg=color) def _setFontComponent(self, which, value): font = list(self.font) font[which] = value self.font = tuple(font) if self.entry: self.entry.config(font=self.font) def setFace(self, face): if face in ['helvetica','arial','courier','times roman']: self._setFontComponent(0, face) else: raise GraphicsError(BAD_OPTION) def setSize(self, size): if 5 <= size <= 36: self._setFontComponent(1,size) else: raise GraphicsError(BAD_OPTION) def setStyle(self, style): if style in ['bold','normal','italic', 'bold italic']: self._setFontComponent(2,style) else: raise GraphicsError(BAD_OPTION) def setTextColor(self, color): self.color=color if self.entry: self.entry.config(fg=color) class Image(GraphicsObject): idCount = 0 imageCache = {} # tk photoimages go here to avoid GC while drawn def __init__(self, p, *pixmap): GraphicsObject.__init__(self, []) self.anchor = p.clone() self.imageId = Image.idCount Image.idCount = Image.idCount + 1 if len(pixmap) == 1: # file name provided self.img = tk.PhotoImage(file=pixmap[0], master=_root) else: # width and height provided width, height = pixmap self.img = tk.PhotoImage(master=_root, width=width, height=height) def _draw(self, canvas, options): p = self.anchor x,y = canvas.toScreen(p.x,p.y) self.imageCache[self.imageId] = self.img # save a reference return canvas.create_image(x,y,image=self.img) def _move(self, dx, dy): self.anchor.move(dx,dy) def undraw(self): try: del self.imageCache[self.imageId] # allow gc of tk photoimage except KeyError: pass GraphicsObject.undraw(self) def getAnchor(self): return self.anchor.clone() def clone(self): other = Image(Point(0,0), 0, 0) other.img = self.img.copy() other.anchor = self.anchor.clone() other.config = self.config.copy() return other def getWidth(self): """Returns the width of the image in pixels""" return self.img.width() def getHeight(self): """Returns the height of the image in pixels""" return self.img.height() def getPixel(self, x, y): """Returns a list [r,g,b] with the RGB color values for pixel (x,y) r,g,b are in range(256) """ value = self.img.get(x,y) if type(value) == type(0): return [value, value, value] else: return list(map(int, value.split())) def setPixel(self, x, y, color): """Sets pixel (x,y) to the given color """ self.img.put("{" + color +"}", (x, y)) def save(self, filename): """Saves the pixmap image to filename. The format for the save image is determined from the filname extension. """ path, name = os.path.split(filename) ext = name.split(".")[-1] self.img.write( filename, format=ext) def color_rgb(r,g,b): """r,g,b are intensities of red, green, and blue in range(256) Returns color specifier string for the resulting color""" return "#%02x%02x%02x" % (r,g,b) def test(): win = GraphWin() win.setCoords(0,0,10,10) t = Text(Point(5,5), "Centered Text") t.draw(win) p = Polygon(Point(1,1), Point(5,3), Point(2,7)) p.draw(win) e = Entry(Point(5,6), 10) e.draw(win) win.getMouse() p.setFill("red") p.setOutline("blue") p.setWidth(2) s = "" for pt in p.getPoints(): s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY()) t.setText(e.getText()) e.setFill("green") e.setText("Spam!") e.move(2,0) win.getMouse() p.move(2,3) s = "" for pt in p.getPoints(): s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY()) t.setText(s) win.getMouse() p.undraw() e.undraw() t.setStyle("bold") win.getMouse() t.setStyle("normal") win.getMouse() t.setStyle("italic") win.getMouse() t.setStyle("bold italic") win.getMouse() t.setSize(14) win.getMouse() t.setFace("arial") t.setSize(20) win.getMouse() win.close() if __name__ == "__main__": test()
Python
''' Created on 2012-10-15 @author: wangxin ''' import sys import os import re import time import md5 import random import thread from sets import Set import socket import traceback from Tkinter import * #record the path #action: # DELETE=0 # INSERT=1 # SUBSTITUTION=2 # SAMEVALUE=3 class Path: def __init__(self, i, j, action): self.i=i self.j=j self.action=action def get_i_index(self): return self.i def get_j_index(self): return self.j def get_action_value(self): return self.action class Edit_Distance: def __init__(self,strA,strB,cdel,cins,csub,CHAR_WIDTH): self.strA=strA self.strB=strB self.cdel=cdel self.cins=cins self.csub=csub self.CHAR_WIDTH=CHAR_WIDTH self.is_eidted=False #comput the distance of two strings #cdel: the cost of deleting #cins: the cost of inserting #csub: the cost of substitution def edit_distance(self,strA,strB,cdel,cins,csub): m=len(strA) n=len(strB) self.dist= [[0 for col in range(n+1)] for row in range(m+1)] self.backtrack_dist=[[0 for col in range(n+1)] for row in range(m+1)] #for backtrack matrix #initial the array self.dist[0][0]=0 self.backtrack_dist[0][0]='0' i=1 while i<=n: self.dist[0][i]=self.dist[0][i-1]+cins self.backtrack_dist[0][i]='-' i=i+1 i=1 while i<=m: self.dist[i][0]=self.dist[i-1][0]+cdel self.backtrack_dist[i][0]='|' i=i+1 j=1 i=1 while j<=n: while i<=m: if strA[i-1]==strB[j-1]: #D[i][j]=min(D[i-1][j-1],D[i-1][j]+1,D[i][j-1]+1); self.dist[i][j]=min(self.dist[i-1][j-1],self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins) #compute backtrack matrix if self.dist[i][j] == self.dist[i-1][j-1] : self.backtrack_dist[i][j]='\\' elif self.dist[i][j] == self.dist[i-1][j]+cdel : self.backtrack_dist[i][j]='|' else: self.backtrack_dist[i][j]='-' #print self.dist[i][j] else: self.dist[i][j]=min(self.dist[i-1][j-1]+csub,self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins) #compute backtrack matrix if self.dist[i][j] == self.dist[i-1][j-1]+csub : self.backtrack_dist[i][j]='\\' elif self.dist[i][j] == self.dist[i-1][j]+cdel : self.backtrack_dist[i][j]='|' else: self.backtrack_dist[i][j]='-' #print self.dist[i][j] i=i+1 i=1 j=j+1 #return self.dist #return the fixed width string def fiexed_width(self,onestr): tmplen=len(str(onestr)) nullstr="" while tmplen<=self.CHAR_WIDTH: nullstr=nullstr+" " tmplen=tmplen+1 onestr=nullstr+str(onestr) # if len(onestr)>self.CHAR_WIDTH: # onestr=onestr[0:self.CHAR_WIDTH-1] return onestr def get_matrix_strvalue(self,ary_matrix,strA,strB): m=len(strA) n=len(strB) #print "valuse:"+str(ary_matrix[2][3]) #get the first line value tmpstr="" tmpstr=tmpstr+self.fiexed_width("")+self.fiexed_width("") i=0 while i<n: tmpstr=tmpstr+self.fiexed_width(strB[i]) i=i+1 tmpstr=tmpstr+"\n" print "m="+str(m) print "n="+str(n) print "tmpstr="+str(tmpstr) j=0 i=0 while j<=m: if j==0: #second line tmpstr=tmpstr+self.fiexed_width("") else: tmpstr=tmpstr+self.fiexed_width(strA[j-1]) print strA[j-1] i=0 while i<=n: tmpstr=tmpstr+self.fiexed_width(str(ary_matrix[j][i])) i=i+1 tmpstr=tmpstr+"\n" j=j+1 return tmpstr #compute the alignment of two strings def get_alignment_value(self,ary_matrix,strA,strB): m=len(strA) n=len(strB) #action value DELETE=0 INSERT=1 SUBSTITUTION=2 SAMEVALUE=3 #declare one array to store the actions self.action_ary=[] i=m j=n #self.action_ary[0]=Path(0,0,SAMEVALUE) print "dist[m][n]:"+str(self.dist[m][n]) while i!=0 and j!=0: tmp1=tmp2=tmp3=1234567 #set big value if i-1>=0 and j-1>=0: tmp1=self.dist[i-1][j-1] if i-1>=0: tmp2=self.dist[i-1][j] if j-1>=0: tmp3=self.dist[i][j-1] minv=min(tmp1,tmp2,tmp3) curv=self.dist[i][j] if minv==tmp1: if curv==minv: self.action_ary.append(Path(i,j,SAMEVALUE)) print "same:"+str(i)+" "+str(j) elif curv==minv+2: self.action_ary.append(Path(i,j,SUBSTITUTION)) print "sub:"+str(i)+" "+str(j) i=i-1 j=j-1 elif minv==tmp2: self.action_ary.append(Path(i,j,DELETE)) print "delete:"+str(i)+" "+str(j) i=i-1 elif minv==tmp3: self.action_ary.append(Path(i,j,INSERT)) print "insert:"+str(i)+" "+str(j) j=j-1 #compute the alignment string result tmpstr="" oriStr="" destStr="" sameStr="" tmpstr=tmpstr+self.fiexed_width("") i=len(self.action_ary)-1 print "len:"+str(i) is_append=False while i>=0: onePath=self.action_ary[i] print "i:"+str(i) print "onePath:"+str(onePath.get_i_index())+" "+str(onePath.get_j_index())+" "+str(onePath.get_action_value()) if onePath.get_action_value()==DELETE: print "delete" if onePath.get_i_index()==len(strA): oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1]) else: oriStr=oriStr+self.fiexed_width("-") sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==INSERT: print "insert" oriStr=oriStr+self.fiexed_width("-") #destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==SUBSTITUTION: print "sub" oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1]) #destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==SAMEVALUE: print "same" oriStr=oriStr+self.fiexed_width(str(strA[onePath.get_i_index()-1])) #destStr=destStr+self.fiexed_width(str(strB[onePath.get_j_index()-1])) sameStr=sameStr+self.fiexed_width("|") if onePath.get_j_index()==len(strB) and is_append==False: destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) is_append=True elif is_append==False: destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) else: destStr=destStr+self.fiexed_width("-") i=i-1 print "oristr:"+oriStr print "destStr:"+destStr print "same:"+sameStr tmpstr=tmpstr+oriStr+"\n" tmpstr=tmpstr+self.fiexed_width("")+sameStr+"\n" tmpstr=tmpstr+self.fiexed_width("")+destStr+"\n" return tmpstr #return full edit distance matrix valuse def get_full_edit_distance_matrix_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "full edit distance matrix:\n"+self.get_matrix_strvalue(self.dist,self.strA,self.strB)+"\n" #return full edit distance matrix valuse def get_backtrack_matrix_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "backtrack matrix:\n"+self.get_matrix_strvalue(self.backtrack_dist,self.strA,self.strB)+"\n" #return full edit distance matrix valuse def get_alignment_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "alignment:\n"+self.get_alignment_value(self.dist,self.strA,self.strB)+"\n" def get_edit_distance(self): return "\n edit distance:"+str(self.dist[len(self.strA)][len(self.strB)])+"\n" #global variable def btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text): print "strA:"+strA.get() print "strB:"+strB.get() print "cdel:"+str(cdel.get()) print "cins:"+str(cins.get()) print "csub:"+str(csub.get()) print "CheckVar1:"+str(CheckVar1.get()) print "CheckVar2:"+str(CheckVar2.get()) print "CheckVar3:"+str(CheckVar3.get()) edit_dist=Edit_Distance(strA.get(),strB.get(),cdel.get(),cins.get(),csub.get(),5) #matrix_strvalue=edit_dist.get_backtrack_matrix_result() if CheckVar1.get()==1: full_matrix_strvalue=edit_dist.get_full_edit_distance_matrix_result() text.insert(INSERT, full_matrix_strvalue) if CheckVar2.get()==1: backtrack_matrix_strvalue=edit_dist.get_backtrack_matrix_result() text.insert(INSERT, backtrack_matrix_strvalue) if CheckVar3.get()==1: alignment_matrix_strvalue=edit_dist.get_alignment_result() text.insert(INSERT, alignment_matrix_strvalue) edit_distance=edit_dist.get_edit_distance() text.insert(INSERT,edit_distance) if __name__ == '__main__': #ary= [[0 for col in range(5)] for row in range(3)] # strA="compare" # strB="computer" # # # m=len(strA) # n=len(strB) # edit_dist=Edit_Distance(strA,strB,1,1,2,5) # #matrix_strvalue=edit_dist.get_backtrack_matrix_result() # matrix_strvalue=edit_dist.get_alignment_result() # print len(matrix_strvalue) matrix_strvalue="" root = Tk() # w = Label(root, text="Hello, world!") # t = Text(root,width=20,height=10) # t.insert(1.0,'56789\n') # t.insert(3.2,'56789') # t.pack() ,width=m+2,height=(n+2)*5 frame= Frame(height = 2000,width = 600,bg = 'red') scrollbar = Scrollbar(frame) scrollbar.pack( side = RIGHT, fill=Y ) text = Text(frame,yscrollcommand = scrollbar.set) text.insert(INSERT, matrix_strvalue) #text.insert(END, "Bye Bye.....") text.pack(side = LEFT, fill = BOTH ) scrollbar.config( command = text.yview ) frame.pack() fm = [] #fram 1 fm.append(Frame(height = 20,width = 400,bg = 'red')) Label(fm[0], text=" first string:").pack(side = LEFT) strA= StringVar() Entry(fm[0] ,textvariable =strA).pack(side = RIGHT) #fram 2 fm.append(Frame(height = 20,width = 400,bg = 'red')) Label(fm[1], text="second string:").pack(side = LEFT) strB= StringVar() Entry(fm[1] ,textvariable =strB).pack(side = RIGHT) #fram 3 fm.append(Frame(height = 20,width = 400)) cdel=IntVar() cins=IntVar() csub=IntVar() Label(fm[2], text="cdel:").pack(side = LEFT) Scale(fm[2],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cdel).pack(side = RIGHT) #fram 4 fm.append(Frame(height = 20,width = 400)) Label(fm[3], text="cins:").pack(side = LEFT) Scale(fm[3],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cins).pack(side = RIGHT) #fram 5 fm.append(Frame(height = 20,width = 400)) Label(fm[4], text="csub:").pack(side = LEFT) Scale(fm[4],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = csub).pack(side = RIGHT) #fram 6 fm.append(Frame(height = 20,width = 400)) CheckVar1 = IntVar() CheckVar2 = IntVar() CheckVar3 =IntVar() C1 = Checkbutton(fm[5], text = "distance matrix", variable = CheckVar1, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C2 = Checkbutton(fm[5], text = "backtrack matrix", variable = CheckVar2, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C3 = Checkbutton(fm[5], text = "alignment", variable = CheckVar3, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C1.pack(side = LEFT) C2.pack(side = LEFT) C3.pack(side = LEFT) #fram 7 fm.append(Frame(height = 20,width = 400)) Button(fm[6],text = 'Calculate ',command =lambda : btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text)).pack() #pack the frame fm[0].pack() fm[1].pack() fm[2].pack() fm[3].pack() fm[4].pack() fm[5].pack() fm[6].pack() root.mainloop()
Python
import sys import os import re import time import md5 import random import thread from sets import Set import socket import traceback from Tkinter import * #record the path #action: # DELETE=0 # INSERT=1 # SUBSTITUTION=2 # SAMEVALUE=3 class Path: def __init__(self, i, j, action): self.i=i self.j=j self.action=action def get_i_index(self): return self.i def get_j_index(self): return self.j def get_action_value(self): return self.action class Edit_Distance: def __init__(self,strA,strB,cdel,cins,csub,CHAR_WIDTH): self.strA=strA self.strB=strB self.cdel=cdel self.cins=cins self.csub=csub self.CHAR_WIDTH=CHAR_WIDTH self.is_eidted=False #comput the distance of two strings #cdel: the cost of deleting #cins: the cost of inserting #csub: the cost of substitution def edit_distance(self,strA,strB,cdel,cins,csub): m=len(strA) n=len(strB) self.dist= [[0 for col in range(n+1)] for row in range(m+1)] self.backtrack_dist=[[0 for col in range(n+1)] for row in range(m+1)] #for backtrack matrix #initial the array self.dist[0][0]=0 self.backtrack_dist[0][0]='0' i=1 while i<=n: self.dist[0][i]=self.dist[0][i-1]+cins self.backtrack_dist[0][i]='-' i=i+1 i=1 while i<=m: self.dist[i][0]=self.dist[i-1][0]+cdel self.backtrack_dist[i][0]='|' i=i+1 j=1 i=1 while j<=n: while i<=m: if strA[i-1]==strB[j-1]: #D[i][j]=min(D[i-1][j-1],D[i-1][j]+1,D[i][j-1]+1); self.dist[i][j]=min(self.dist[i-1][j-1],self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins) #compute backtrack matrix if self.dist[i][j] == self.dist[i-1][j-1] : self.backtrack_dist[i][j]='\\' elif self.dist[i][j] == self.dist[i-1][j]+cdel : self.backtrack_dist[i][j]='|' else: self.backtrack_dist[i][j]='-' #print self.dist[i][j] else: self.dist[i][j]=min(self.dist[i-1][j-1]+csub,self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins) #compute backtrack matrix if self.dist[i][j] == self.dist[i-1][j-1]+csub : self.backtrack_dist[i][j]='\\' elif self.dist[i][j] == self.dist[i-1][j]+cdel : self.backtrack_dist[i][j]='|' else: self.backtrack_dist[i][j]='-' #print self.dist[i][j] i=i+1 i=1 j=j+1 #return self.dist #return the fixed width string def fiexed_width(self,onestr): tmplen=len(str(onestr)) nullstr="" while tmplen<=self.CHAR_WIDTH: nullstr=nullstr+" " tmplen=tmplen+1 onestr=nullstr+str(onestr) # if len(onestr)>self.CHAR_WIDTH: # onestr=onestr[0:self.CHAR_WIDTH-1] return onestr def get_matrix_strvalue(self,ary_matrix,strA,strB): m=len(strA) n=len(strB) #print "valuse:"+str(ary_matrix[2][3]) #get the first line value tmpstr="" tmpstr=tmpstr+self.fiexed_width("")+self.fiexed_width("") i=0 while i<n: tmpstr=tmpstr+self.fiexed_width(strB[i]) i=i+1 tmpstr=tmpstr+"\n" # print "m="+str(m) # print "n="+str(n) # print "tmpstr="+str(tmpstr) j=0 i=0 while j<=m: if j==0: #second line tmpstr=tmpstr+self.fiexed_width("") else: tmpstr=tmpstr+self.fiexed_width(strA[j-1]) print strA[j-1] i=0 while i<=n: tmpstr=tmpstr+self.fiexed_width(str(ary_matrix[j][i])) i=i+1 tmpstr=tmpstr+"\n" j=j+1 return tmpstr #compute the alignment of two strings def get_alignment_value(self,ary_matrix,strA,strB): m=len(strA) n=len(strB) #action value DELETE=0 INSERT=1 SUBSTITUTION=2 SAMEVALUE=3 #declare one array to store the actions self.action_ary=[] i=m j=n #self.action_ary[0]=Path(0,0,SAMEVALUE) print "dist[m][n]:"+str(self.dist[m][n]) while i!=0 and j!=0: tmp1=tmp2=tmp3=999999999 #set big value if i-1>=0 and j-1>=0: tmp1=self.dist[i-1][j-1] if i-1>=0: tmp2=self.dist[i-1][j] if j-1>=0: tmp3=self.dist[i][j-1] minv=min(tmp1,tmp2,tmp3) curv=self.dist[i][j] if minv==tmp1: if curv==minv: self.action_ary.append(Path(i,j,SAMEVALUE)) # print "same:"+str(i)+" "+str(j) elif curv==minv+2: self.action_ary.append(Path(i,j,SUBSTITUTION)) # print "sub:"+str(i)+" "+str(j) i=i-1 j=j-1 elif minv==tmp2: self.action_ary.append(Path(i,j,DELETE)) # print "delete:"+str(i)+" "+str(j) i=i-1 elif minv==tmp3: self.action_ary.append(Path(i,j,INSERT)) # print "insert:"+str(i)+" "+str(j) j=j-1 #compute the alignment string result tmpstr="" oriStr="" destStr="" sameStr="" tmpstr=tmpstr+self.fiexed_width("") i=len(self.action_ary)-1 # print "len:"+str(i) is_append=False while i>=0: onePath=self.action_ary[i] # print "i:"+str(i) # print "onePath:"+str(onePath.get_i_index())+" "+str(onePath.get_j_index())+" "+str(onePath.get_action_value()) if onePath.get_action_value()==DELETE: # print "delete" if onePath.get_i_index()==len(strA): oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1]) else: oriStr=oriStr+self.fiexed_width("-") sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==INSERT: # print "insert" oriStr=oriStr+self.fiexed_width("-") #destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==SUBSTITUTION: # print "sub" oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1]) #destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) sameStr=sameStr+self.fiexed_width(" ") elif onePath.get_action_value()==SAMEVALUE: # print "same" oriStr=oriStr+self.fiexed_width(str(strA[onePath.get_i_index()-1])) #destStr=destStr+self.fiexed_width(str(strB[onePath.get_j_index()-1])) sameStr=sameStr+self.fiexed_width("|") if onePath.get_j_index()==len(strB) and is_append==False: destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) is_append=True elif is_append==False: destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1]) else: destStr=destStr+self.fiexed_width("-") i=i-1 # print "oristr:"+oriStr # print "destStr:"+destStr # print "same:"+sameStr tmpstr=tmpstr+oriStr+"\n" tmpstr=tmpstr+self.fiexed_width("")+sameStr+"\n" tmpstr=tmpstr+self.fiexed_width("")+destStr+"\n" return tmpstr #return full edit distance matrix valuse def get_full_edit_distance_matrix_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "full edit distance matrix:\n"+self.get_matrix_strvalue(self.dist,self.strA,self.strB)+"\n" #return full edit distance matrix valuse def get_backtrack_matrix_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "backtrack matrix:\n"+self.get_matrix_strvalue(self.backtrack_dist,self.strA,self.strB)+"\n" #return full edit distance matrix valuse def get_alignment_result(self): if self.is_eidted==False: self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub) self.is_eidted=True return "alignment:\n"+self.get_alignment_value(self.dist,self.strA,self.strB)+"\n" def get_edit_distance(self): return "\n edit distance:"+str(self.dist[len(self.strA)][len(self.strB)])+"\n" #global variable def btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text): # print "strA:"+strA.get() # print "strB:"+strB.get() # print "cdel:"+str(cdel.get()) # print "cins:"+str(cins.get()) # print "csub:"+str(csub.get()) # print "CheckVar1:"+str(CheckVar1.get()) # print "CheckVar2:"+str(CheckVar2.get()) # print "CheckVar3:"+str(CheckVar3.get()) edit_dist=Edit_Distance(strA.get(),strB.get(),cdel.get(),cins.get(),csub.get(),5) #matrix_strvalue=edit_dist.get_backtrack_matrix_result() if CheckVar1.get()==1: full_matrix_strvalue=edit_dist.get_full_edit_distance_matrix_result() text.insert(INSERT, full_matrix_strvalue) if CheckVar2.get()==1: backtrack_matrix_strvalue=edit_dist.get_backtrack_matrix_result() text.insert(INSERT, backtrack_matrix_strvalue) if CheckVar3.get()==1: alignment_matrix_strvalue=edit_dist.get_alignment_result() text.insert(INSERT, alignment_matrix_strvalue) edit_distance=edit_dist.get_edit_distance() text.insert(INSERT,edit_distance) if __name__ == '__main__': #ary= [[0 for col in range(5)] for row in range(3)] # strA="compare" # strB="computer" # # # m=len(strA) # n=len(strB) # edit_dist=Edit_Distance(strA,strB,1,1,2,5) # #matrix_strvalue=edit_dist.get_backtrack_matrix_result() # matrix_strvalue=edit_dist.get_alignment_result() # print len(matrix_strvalue) matrix_strvalue="" root = Tk() # w = Label(root, text="Hello, world!") # t = Text(root,width=20,height=10) # t.insert(1.0,'56789\n') # t.insert(3.2,'56789') # t.pack() ,width=m+2,height=(n+2)*5 frame= Frame(height = 2000,width = 600,bg = 'red') scrollbar = Scrollbar(frame) scrollbar.pack( side = RIGHT, fill=Y ) text = Text(frame,yscrollcommand = scrollbar.set) text.insert(INSERT, matrix_strvalue) text.pack(side = LEFT, fill = BOTH ) scrollbar.config( command = text.yview ) frame.pack() fm = [] #fram 1 fm.append(Frame(height = 20,width = 400,bg = 'red')) Label(fm[0], text=" first string:").pack(side = LEFT) strA= StringVar() Entry(fm[0] ,textvariable =strA).pack(side = RIGHT) #fram 2 fm.append(Frame(height = 20,width = 400,bg = 'red')) Label(fm[1], text="second string:").pack(side = LEFT) strB= StringVar() Entry(fm[1] ,textvariable =strB).pack(side = RIGHT) #fram 3 fm.append(Frame(height = 20,width = 400)) cdel=IntVar() cins=IntVar() csub=IntVar() Label(fm[2], text="cdel:").pack(side = LEFT) Scale(fm[2],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cdel).pack(side = RIGHT) #fram 4 fm.append(Frame(height = 20,width = 400)) Label(fm[3], text="cins:").pack(side = LEFT) Scale(fm[3],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cins).pack(side = RIGHT) #fram 5 fm.append(Frame(height = 20,width = 400)) Label(fm[4], text="csub:").pack(side = LEFT) Scale(fm[4],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = csub).pack(side = RIGHT) #fram 6 fm.append(Frame(height = 20,width = 400)) CheckVar1 = IntVar() CheckVar2 = IntVar() CheckVar3 =IntVar() C1 = Checkbutton(fm[5], text = "distance matrix", variable = CheckVar1, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C2 = Checkbutton(fm[5], text = "backtrack matrix", variable = CheckVar2, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C3 = Checkbutton(fm[5], text = "alignment", variable = CheckVar3, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C1.pack(side = LEFT) C2.pack(side = LEFT) C3.pack(side = LEFT) #fram 7 fm.append(Frame(height = 20,width = 400)) Button(fm[6],text = 'Calculate ',command =lambda : btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text)).pack() #pack the frame fm[0].pack() fm[1].pack() fm[2].pack() fm[3].pack() fm[4].pack() fm[5].pack() fm[6].pack() root.mainloop()
Python
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#!/usr/bin/env python import gzip, sys, threading import crawle class SaveURLHandler(crawle.Handler): """This handler simply saves all pages. into a gziped file. Any reponses with status other than 200 is placed back on the queue. This example also demonstrates the importance of synchronization as multiple threads can attempt to write to the file conncurrently. """ def __init__(self, output): self.output = gzip.open(output,'ab') self.lock = threading.Lock() self.exit = False def process(self, req_res, queue): if not req_res.response_status: print req_res.error return if req_res.response_status != 200: print "%d - putting %s back on queue" % (req_res.response_status, req_res.response_url) queue.put(req_res.response_url) else: self.lock.acquire() if self.exit: self.lock.release() return self.output.write(req_res.response_body) self.output.write("===*===\n") self.lock.release() def stop(self): self.exit = True self.output.close() if __name__ == '__main__': crawle.run_crawle(sys.argv, handler=SaveURLHandler('output.gz'))
Python
#!/usr/bin/env python import getpass, re, sys, threading import crawle class TwitterHandler(crawle.Handler): """This is an example of doing authentication with CRAWL-E. It must first be noted that twitter's robots.txt file disallows crawling thus proceed at your own risk. """ TWITTER_SESS_RE = re.compile('(_twitter_sess=[^;]+;)') AUTH_TOKEN_RE = re.compile('<input id="authenticity_token" name="authenticity_token" type="hidden" value="([a-z0-9]+)"') LOGIN_PAGE_URL = 'http://twitter.com/login' LOGIN_POST_URL = 'https://twitter.com/sessions' def __init__(self, username, password): self.username = username self.password = password self.session = None self.lock = threading.Lock() self.exit = False def login(self, body): """ Using CRAWL-E's connection framework authenticate with Twitter and extract cookie data""" match = self.AUTH_TOKEN_RE.search(body) if not match or len(match.groups()) != 1: return False auth_token = match.group(1) params = {'authenticity_token':auth_token, 'session[username_or_email]':self.username, 'session[password]':self.password, 'commit':'Sign In'} cc = crawle.HTTPConnectionControl(crawle.Handler()) rr = crawle.RequestResponse(self.LOGIN_POST_URL, method='POST', params=params, redirects=None) cc.request(rr) if rr.response_status != 302: return False match = self.TWITTER_SESS_RE.search(rr.response_headers['set-cookie']) if not match or len(match.groups()) != 1: return False self.session = match.group(1) return True def pre_process(self, req_res): self.lock.acquire() if self.session: req_res.request_headers = {'cookie':self.session} self.lock.release() def process(self, req_res, queue): if req_res.response_status != 200: print "%d - putting %s back on queue" % (req_res.response_status, req_res.response_url) queue.put(req_res.response_url) return # Test if a login is required, if so login then readd the request URL if req_res.response_url == self.LOGIN_PAGE_URL: self.lock.acquire() login_status = self.login(req_res.response_body) self.lock.release() if login_status: queue.put(req_res.request_url) else: print 'Login failed' return print req_res.response_body return def stop(self): self.exit = True self.output.close() if __name__ == '__main__': print "This is broken for now" sys.exit(1) username = raw_input('Username: ') password = getpass.getpass() twitter_handler = TwitterHandler(username, password) queue = crawle.URLQueue() queue.queue.put('http://twitter.com/following') controller = crawle.Controller(handler=twitter_handler, queue=queue, num_threads=1) controller.start() try: controller.join() except KeyboardInterrupt: controller.stop() queue.save('uncrawled_urls')
Python
#!/usr/bin/env python from distutils.core import setup from crawle import VERSION setup(name='CRAWL-E', version=VERSION, description='Highly distributed web crawling framework', author='Bryce Boe', author_email='bboe (_at_) cs.ucsb.edu', url='http://code.google.com/p/crawl-e', py_modules = ['crawle'] )
Python
"""CRAWL-E is a highly distributed web crawling framework.""" import Queue, cStringIO, gzip, httplib, logging, mimetypes, resource, socket import sys, subprocess, threading, time, urllib, urlparse from optparse import OptionParser VERSION = '0.6.4' HEADER_DEFAULTS = {'Accept':'*/*', 'Accept-Language':'en-us,en;q=0.8', 'User-Agent':'CRAWL-E/%s' % VERSION} DEFAULT_SOCKET_TIMEOUT = 30 STOP_CRAWLE = False class CrawleException(Exception): """Base Crawle exception class.""" class CrawleRequestAborted(CrawleException): """Exception raised when the handler pre_process function sets the response_url to None to indicate not to visit the URL.""" class CrawleStopped(CrawleException): """Exception raised when the crawler is stopped.""" class CrawleUnsupportedScheme(CrawleException): """Exception raised when the url does not start with "http" or "https".""" class CrawleRedirectsExceeded(CrawleException): """Exception raised when the number of redirects exceeds the limit.""" class Handler(object): """An _abstract_ class for handling what urls to retrieve and how to parse and save them. The functions of this class need to be designed in such a way so that they are threadsafe as multiple threads will have access to the same instance. """ def pre_process(self, request_response): """pre_process is called directly before making the reqeust. Any of the request parameters can be modified here. Setting the responseURL to None will cause the request to be dropped. This is useful for testing if a redirect link should be followed. """ return def process(self, request_response, queue): """Process is called after the request has been made. It needs to be implemented by a subclass. Keyword Arguments: request_response -- the request response object queue -- the handler to the queue class """ assert request_response and queue # pychecker hack raise NotImplementedError(' '.join(('Handler.process must be defined', 'in a subclass'))) class RequestResponse(object): """This class is a container for information pertaining to requests and responses.""" def __init__(self, url, headers=None, method='GET', params=None, files=None, redirects=10): """Constructs a RequestResponse object. Keyword Arguments: url -- The url to request. headers -- The http request headers. method -- The http request method. params -- The http parameters as a dictionary. files -- A list of tuples containing key, filename, filedata redirects -- The maximum number of redirects to follow. """ self.error = None self.redirects = redirects self.extra = [] self.request_headers = headers self.request_url = url self.request_method = method self.request_params = params self.request_files = files self.response_status = None self.response_url = url self.response_headers = None self.response_body = None self.response_time = None class HTTPConnectionQueue(object): """This class handles the queue of sockets for a particular address. This essentially is a queue of socket objects which also adds a transparent field to each connection object which is the request_count. When the request_count exceeds the REQUEST_LIMIT the connection is automatically reset. """ REQUEST_LIMIT = None @staticmethod def connection_object(address, encrypted): """Very simply return a HTTP(S)Connection object.""" if encrypted: connection = httplib.HTTPSConnection(*address) else: connection = httplib.HTTPConnection(*address) connection.request_count = 0 return connection def __init__(self, address, encrypted=False, max_conn=None): """Constructs a HTTPConnectionQueue object. Keyword Arguments: address -- The address for which this object maps to. encrypted -- Where or not the connection is encrypted. max_conn -- The maximum number of connections to maintain """ self.address = address self.encrypted = encrypted self.queue = Queue.Queue(0) self.connections = 0 self.max_conn = max_conn def destroy(self): """Destroy the HTTPConnectionQueue object.""" try: while True: connection = self.queue.get(block=False) connection.close() except Queue.Empty: pass def get(self): """Return a HTTP(S)Connection object for the appropriate address. First try to return the object from the queue, however if the queue is empty create a new socket object to return. Dynamically add new field to HTTPConnection called request_count to keep track of the number of requests made with the specific connection. """ try: connection = self.queue.get(block=False) self.connections -= 1 # Reset the connection if exceeds request limit if (self.REQUEST_LIMIT and connection.request_count >= self.REQUEST_LIMIT): connection.close() connection = HTTPConnectionQueue.connection_object( self.address, self.encrypted) except Queue.Empty: connection = HTTPConnectionQueue.connection_object(self.address, self.encrypted) return connection def put(self, connection): """Put the HTTPConnection object back on the queue.""" connection.request_count += 1 if self.max_conn != None and self.connections + 1 > self.max_conn: connection.close() else: self.queue.put(connection) self.connections += 1 class QueueNode(object): """This class handles an individual node in the CQueueLRU.""" def __init__(self, connection_queue, key, next=None): """Construct a QueueNode object. Keyword Arguments: connection_queue -- The ConnectionQueue object. key -- The unique identifier that allows one to perform a reverse lookup in the hash table. next -- The previous least recently used item. """ self.connection_queue = connection_queue self.key = key self.next = next if next: self.next.prev = self self.prev = None def remove(self): """Properly remove the node""" if self.prev: self.prev.next = None self.connection_queue.destroy() class CQueueLRU(object): """This class manages a least recently used list with dictionary lookup.""" def __init__(self, max_queues=None, max_conn=None): """Construct a CQueueLRU object. Keyword Arguments: max_queues -- The maximum number of unique queues to manage. When only crawling a single domain, one should be sufficient. max_conn -- The maximum number of connections that may persist within a single ConnectionQueue. """ self.lock = threading.Lock() self.max_queues = max_queues self.max_conn = max_conn self.table = {} self.newest = None self.oldest = None def __getitem__(self, key): """Return either a HTTP(S)Connection object. Fetches an already utilized object if one exists. """ self.lock.acquire() if key in self.table: connection = self.table[key].connection_queue.get() else: connection = HTTPConnectionQueue.connection_object(*key) self.lock.release() return connection def __setitem__(self, key, connection): """Store the HTTP(S)Connection object. This function ensures that there are at most max_queues. In the event there are too many, the oldest inactive queues will be deleted. """ self.lock.acquire() if key in self.table: node = self.table[key] # move the node to the head of the list if self.newest != node: node.prev.next = node.next if self.oldest != node: node.next.prev = node.prev else: self.oldest = node.prev node.prev = None node.next = self.newest self.newest = node.next.prev = node else: # delete the oldest while too many while (self.max_queues != None and len(self.table) + 1 > self.max_queues): if self.oldest == self.newest: self.newest = None del self.table[self.oldest.key] prev = self.oldest.prev self.oldest.remove() self.oldest = prev connection_queue = HTTPConnectionQueue(*key, max_conn=self.max_conn) node = QueueNode(connection_queue, key, self.newest) self.newest = node if not self.oldest: self.oldest = node self.table[key] = node node.connection_queue.put(connection) self.lock.release() class HTTPConnectionControl(object): """This class handles HTTPConnectionQueues by storing a queue in a dictionary with the address as the index to the dictionary. Additionally this class handles resetting the connection when it reaches a specified request limit. """ def __init__(self, handler, max_queues=None, max_conn=None, timeout=None): """Constructs the HTTPConnection Control object. These objects are to be shared between each thread. Keyword Arguments: handler -- The Handler class for checking if a url is valid. max_queues -- The maximum number of connection_queues to maintain. max_conn -- The maximum number of connections (sockets) allowed for a given connection_queue. timeout -- The socket timeout value. """ socket.setdefaulttimeout(timeout) self.cq_lru = CQueueLRU(max_queues, max_conn) self.handler = handler def _build_request(self, req_res): """Construct request headers and URI from request_response object.""" u = urlparse.urlparse(req_res.response_url) if u.scheme not in ['http', 'https'] or u.netloc == '': raise CrawleUnsupportedScheme() address = socket.gethostbyname(u.hostname), u.port encrypted = u.scheme == 'https' url = urlparse.urlunparse(('', '', u.path, u.params, u.query, '')) if req_res.request_headers: headers = req_res.request_headers else: headers = {} if 'Accept' not in headers: headers['Accept'] = HEADER_DEFAULTS['Accept'] if 'Accept-Encoding' not in headers: headers['Accept-Encoding'] = 'gzip' if 'Accept-Languge' not in headers: headers['Accept-Language'] = HEADER_DEFAULTS['Accept-Language'] if 'Host' not in headers: if u.port == None: headers['Host'] = u.hostname else: headers['Host'] = '%s:%d' % (u.hostname, u.port) if 'User-Agent' not in headers: headers['User-Agent'] = HEADER_DEFAULTS['User-Agent'] return address, encrypted, url, headers def request(self, req_res): """Handles the request to the server.""" if STOP_CRAWLE: raise CrawleStopped() self.handler.pre_process(req_res) if req_res.response_url == None: raise CrawleRequestAborted() address, encrypted, url, headers = self._build_request(req_res) connection = self.cq_lru[(address, encrypted)] try: start = time.time() if req_res.request_files: content_type, data = self.encode_multipart_formdata( req_res.request_params, req_res.request_files) headers['Content-Type'] = content_type elif req_res.request_params: data = urllib.urlencode(req_res.request_params) headers['Content-Type'] = 'application/x-www-form-urlencoded' else: data = '' connection.request(req_res.request_method, url, data, headers) response = connection.getresponse() response_time = time.time() - start response_body = response.read() self.cq_lru[(address, encrypted)] = connection except Exception: connection.close() raise if response.status in (301, 302, 303) and req_res.redirects != None: if req_res.redirects <= 0: raise CrawleRedirectsExceeded() req_res.redirects -= 1 redirect_url = response.getheader('location') req_res.response_url = urlparse.urljoin(req_res.response_url, redirect_url) self.request(req_res) else: req_res.response_time = response_time req_res.response_status = response.status req_res.response_headers = dict(response.getheaders()) if ('content-encoding' in req_res.response_headers and req_res.response_headers['content-encoding'] == 'gzip'): try: fileobj = cStringIO.StringIO(response_body) temp = gzip.GzipFile(fileobj=fileobj) req_res.response_body = temp.read() temp.close() fileobj.close() except IOError: # HACK for pages that append plain text to gzip output sb = subprocess.Popen(['zcat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sb.stdin.write(response_body) sb.stdin.close() req_res.response_body = sb.stdout.read() del sb req_res.extra.append('Used zcat') else: req_res.response_body = response_body # The following function is modified from the snippet at: # http://code.activestate.com/recipes/146306/ def encode_multipart_formdata(self, fields, files): """Encode data properly when files are uploaded. Keyword Arguments: fields -- A dictionary containing key value pairs for form submission files -- A list of tuples with key, filename, file data for form submission. """ default_type = 'application/octet-stream' BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for key, value in fields.items(): L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) content_type = mimetypes.guess_type(filename)[0] or default_type L.append('Content-Type: %s' % content_type) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body class ControlThread(threading.Thread): """A single thread of control""" def __init__(self, connection_control, handler, queue): """Sets up the ControlThread. Keyword Arguments: connection_control -- A HTTPConnectionControl object. This object is shared amongst the threads handler -- The handler class for parsing the returned information queue -- The handle to the queue class which implements get and put. """ threading.Thread.__init__(self) self.connection_control = connection_control self.handler = handler self.queue = queue def run(self): """This is the execution order of a single thread. The threads will stop when STOP_CRAWLE becomes true, or when the queue raises Queue.Empty. """ while not STOP_CRAWLE: try: request_response = self.queue.get() except Queue.Empty: break try: self.connection_control.request(request_response) except Exception, e: request_response.error = e self.handler.process(request_response, self.queue) self.queue.work_complete() class Controller(object): """The primary controller manages all the threads.""" def __init__(self, handler, queue, num_threads=1, timeout=DEFAULT_SOCKET_TIMEOUT): """Create the controller object Keyword Arguments: handler -- The Handler class each thread will use for processing queue -- The handle the the queue class num_threads -- The number of threads to spawn (Default 1) timeout -- The socket timeout time """ nofiles = resource.getrlimit(resource.RLIMIT_NOFILE)[0] queues = nofiles * 2 / (num_threads * 3) self.connection_ctrl = HTTPConnectionControl(handler=handler, max_queues=queues, max_conn=num_threads, timeout=timeout) self.handler = handler self.threads = [] for _ in range(num_threads): thread = ControlThread(handler=handler, queue=queue, connection_control=self.connection_ctrl) self.threads.append(thread) def start(self): """Starts all threads""" for thread in self.threads: thread.start() def join(self): """Join on all threads""" for thread in self.threads: while 1: thread.join(1) if not thread.isAlive(): break def stop(self): """Stops all threads gracefully""" global STOP_CRAWLE STOP_CRAWLE = True self.join() class VisitURLHandler(Handler): """Very simple example handler which simply visits the page. This handler just demonstrates how to interact with the queue. """ def process(self, info, queue): """Puts item back on the queue if the request was no successful.""" if info['status'] != 200: print 'putting %s back on queue' % info['url'] queue.put(info['url']) class CrawlQueue(object): """Crawl Queue is a mostly abstract concurrent Queue class. Users of this class must implement their specific __init__, _get, and _put functions both initialize their queue, get items from the queue, and put items into the queue. The CrawlQueue class takes care of concurrency issues, so that subclass implementations can be assured atomic accesses to the user defined _get and _put functions. As such both the user defined _get and _put functions should be nonblocking. In addition to assuring atomic access, the CrawlQueue class manages the number of outstanding workers so that it only raises Queue.Empty when both its queue it empty and there is no outstanding work. """ def __init__(self, single_threaded=False): """Initializes the CrawlQueue class with a condition variable and container for the numer of workers.""" if not single_threaded: self._lock = threading.Lock() self.cv = threading.Condition(self._lock) else: self.cv = None self._workers = 0 def get(self): """The interface to obtaining an object from the queue. This function manages the concurrency and waits for more items if there is outstanding work, otherwise it raises Queue.Empty. This class should not be overwritten, but rather the user should write a _get class. """ while True: if self.cv: self.cv.acquire() try: item = self._get() self._workers += 1 return item except Queue.Empty: if self._workers == 0: if self.cv: self.cv.notify_all() raise if not self.cv: raise Exception('Invalid single thread handling') self.cv.wait() finally: if self.cv: self.cv.release() def put(self, item): """The interface for putting an item on the queue. This function manages concurrency and notifies other threads when an item is added.""" if self.cv: self.cv.acquire() try: self._put(item) if self.cv: self.cv.notify() finally: if self.cv: self.cv.release() def work_complete(self): """Called by the ControlThread after the user defined handler has returned thus indicating no more items will be added to the queue from that thread before the next call to get.""" if self.cv: self.cv.acquire() if self._workers > 0: self._workers -= 1 if self.cv: self.cv.notify() self.cv.release() def _get(self): """Function to be implemented by the user.""" raise NotImplementedError('CrawlQueue._get() must be implemented') def _put(self, item): """Function to be implemented by the user.""" assert item # pychecker hack raise NotImplementedError('CrawlQueue._put(...) must be implemented') class URLQueue(CrawlQueue): """URLQueue is the most basic queue type and is all that is needed for most situations. Simply, it queues full urls.""" formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) sh.setFormatter(formatter) logger = logging.getLogger('queue') logger.setLevel(logging.DEBUG) logger.addHandler(sh) LOG_STRING = 'Crawled: %d Remaining: %d RPS: %.2f (%.2f avg)' def __init__(self, seed_file=None, seed_urls=None, single_threaded=False, log_after=1000): """Sets up the URLQueue by creating a queue. Keyword arguments: seedfile -- file containing urls to seed the queue (default None) """ super(URLQueue, self).__init__(single_threaded) self.queue = [] self.start_time = self.block_time = None self.total_items = 0 self.log_after = log_after # Add seeded items to the queue if seed_file: try: fp = open(seed_file) except IOError: raise Exception('Could not open seed file') for line in fp: self.queue.append(line.strip()) fp.close() URLQueue.logger.info('Queued: %d from seed file' % len(self.queue)) if seed_urls: [self.queue.put(x) for x in seed_urls] URLQueue.logger.info('Queued: %d from seed url' % len(seed_urls)) if len(self.queue) == 0: URLQueue.logger.info('Starting with empty queue') def save(self, save_file): """Outputs queue to file specified. On error prints queue to screen.""" try: fp = open(save_file, 'w') except IOError: URLQueue.logger.warn('Could not open file for saving.') fp = sys.stdout items = 0 for item in self.queue: fp.write('%s\n' % item) items += 1 if fp != sys.stdout: fp.close() URLQueue.logger.info('Saved %d items.' % items) def _get(self): """Return url at the head of the queue or raise Queue.Empty""" if len(self.queue): url = self.queue.pop(0) self.total_items += 1 if self.start_time == None: self.start_time = self.block_time = time.time() elif (self.log_after and self.total_items % self.log_after == 0): now = time.time() rps_now = self.log_after / (now - self.block_time) rps_avg = self.total_items / (now - self.start_time) log = URLQueue.LOG_STRING % (self.total_items, len(self.queue), rps_now, rps_avg) URLQueue.logger.info(log) self.block_time = now return RequestResponse(url) else: raise Queue.Empty def _put(self, url): """Puts the item back on the queue.""" self.queue.append(url) def quick_request(url, redirects=30, timeout=30): """Convenience function to quickly request a URL within CRAWl-E.""" cc = HTTPConnectionControl(Handler(), timeout=timeout) rr = RequestResponse(url, redirects=redirects) cc.request(rr) return rr def run_crawle(argv, handler, log_after=1): """The typical way to start CRAWL-E""" parser = OptionParser() parser.add_option('-t', '--threads', help='number of threads to use', type='int', default=1) parser.add_option('-s', '--seed', help='file to seed queue with') parser.add_option('-u', '--url', help='url to seed queue with', action='append', metavar='URL', dest='urls') parser.add_option('-S', '--save', help='file to save remaining urls to') options, args = parser.parse_args() queue_handler = URLQueue(seed_file=options.seed, seed_urls=options.urls) controller = Controller(handler=handler, queue=queue_handler, num_threads=options.threads) controller.start() try: controller.join() except KeyboardInterrupt: controller.stop() if options.save: queue_handler.save(options.save) if __name__ == '__main__': """Basic example of how to start CRAWL-E.""" run_crawle(sys.argv, handler=VisitURLHandler())
Python
print("输入:") year=int(input()) print(year) for i in range(1,100): if (year%400==0 or (year%4==0 and year%100!=0)): print('year') else: print("平年!")
Python
#!/usr/bin/python # Filename: using_file.py import re i=1000 poem="" f = open('poem.txt', 'w') # open for 'w'riting while i>0: poem=poem+"B" i=i-1 f.write(poem) # write text to file f.close() # close the file
Python
import ftplib, string import os, sys import threading class MyFTP: def __init__(self, host='', user='', passwd=''): self.host = host self.user = user self.passwd = passwd self.filename = '' self.ftp = ftplib.FTP(host,user,passwd) def download_by_thread(self, filename, threadnum=1, blocksize=8192): self.filename = filename # 获取文件名 onlyname = os.path.basename(filename) cmd = "SIZE "+filename # 取得要下载的文件的大小 ret = self.ftp.sendcmd(cmd) self.ftp.quit() # 计算用多线程下载时,每一个线程应该下载的大小 fsize = int(string.split(ret)[1]) print ('file', filename, 'size:', fsize) rest = None bsize = fsize / threadnum # 创建线程 threads= [] for i in range(0, threadnum-1): begin = bsize * i print (i, begin, bsize) tp = threading.Thread(target=self.download_file, args=(i, filename,begin,bsize,blocksize,rest,)) threads.append(tp) have1 = bsize * threadnum have2 = fsize - have1 lastsize = bsize + have2 begin = bsize * (threadnum-1) print (threadnum-1, begin, lastsize) tp = threading.Thread(target=self.download_file, args=(threadnum-1, filename, begin,lastsize,blocksize,rest,)) threads.append(tp) print ('threads:', len(threads)) for t in threads: t.start() for t in threads: t.join() # 每个线程都下载完成了,合并临时文件为一个文件 fw = open(onlyname, "wb") for i in range(0, threadnum): fname = onlyname+'.part.'+str(i) print (fname) if not os.path.isfile(fname): print ('not found', fname) continue f1 = open(fname, 'rb') while 1: data = f1.read(8192) if not len(data): break fw.write(data) f1.close() os.remove(fname) fw.close() print ('all ok') def download_file(self, inx, filename, begin=0, size=0, blocksize=8192, rest=None): onlyname = os.path.basename(filename) tname = threading.currentThread().getName() #inx = string.split(tname, '-')[-1] # 新建一个连接来下载,每个线程一个连接,注意这里没有考虑有些ftp服务器限制一个ip只能有多少连接的情况。 myftp = ftplib.FTP(self.host,self.user,self.passwd) # 创建临时文件 fp = open(onlyname+'.part.'+str(inx), 'wb') #fp.seek(begin) callback = fp.write haveread = 0 myftp.voidcmd('TYPE I') # 告诉服务器要从文件的哪个位置开始下载 cmd1 = "REST "+str(begin) print (tname, cmd1) ret = myftp.sendcmd(cmd1) # 开始下载 cmd = "RETR "+filename conn = myftp.transfercmd(cmd, rest) readsize = blocksize while 1: if size > 0: last = size - haveread if last > blocksize: readsize = blocksize else: readsize = last data = conn.recv(readsize) if not data: break #callback(fp, data) # 已经下载的数据长度        haveread = haveread + len(data) # 只能下载指定长度的数据,下载到就退出 if (haveread > size): print (tname, 'haveread:', haveread, 'size:', size) hs = haveread - size callback(data[:hs]) break elif haveread == size: callback(data) print (tname, 'haveread:', haveread) break callback(data) conn.close() fp.close() try: ret = myftp.getresp() except Exception: print (tname,e) myftp.quit() return ret ftp = MyFTP("127.0.0.1", 'anonymous', '123') filename='/incoming/cygwin.zip' ftp.download_by_thread(filename, 10)
Python
bigFile= open("big.txt", 'w') bigFile.seek(28132) #大小自己定,需要几个G, fileSize就是几,速度绝对快 bigFile.write('\x00') bigFile.close()
Python
import os def DirFile(rootDir): list_dirs = os.walk(rootDir) for root,dirs,files in list_dirs: for d in dirs: print (os.path.join(root,d)) for f in files: print (os.path.join(root,f)) DirFile('c:')
Python
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) print "%.3lf" % ((a+b+c)/3.0)
Python
from sys import stdin from math import * r, h = map(float, stdin.readline().strip().split()) print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
Python
from sys import stdin from math import * n, = map(int, stdin.readline().strip().split()) rad = radians(n) print "%.3lf %.3lf" % (sin(rad), cos(rad))
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) print n*(n+1)/2
Python
from sys import stdin a, b = map(int, stdin.readline().strip().split()) print b, a
Python
from sys import stdin n, m = map(int, stdin.readline().strip().split()) a = (4*n-m)/2 b = n-a if m % 2 == 1 or a < 0 or b < 0: print "No answer" else: print a, b
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) money = n * 95 if money >= 300: money *= 0.85 print "%.2lf" % money
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) print ["yes", "no"][n % 2]
Python
from sys import stdin from math import * x1, y1, x2, y2 = map(float, stdin.readline().strip().split()) print "%.3lf" % hypot((x1-x2), (y1-y2))
Python
from sys import stdin n = stdin.readline().strip().split()[0] print '%c%c%c' % (n[2], n[1], n[0])
Python
from sys import stdin x, = map(float, stdin.readline().strip().split()) print abs(x)
Python
from sys import stdin from calendar import isleap year, = map(int, stdin.readline().strip().split()) if isleap(year): print "yes" else: print "no"
Python
from sys import stdin f, = map(float, stdin.readline().strip().split()) print "%.3lf" % (5*(f-32)/9)
Python
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes" elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle" else: print "no"
Python
from sys import stdin a = map(int, stdin.readline().strip().split()) a.sort() print a[0], a[1], a[2]
Python
s = i = 0 while True: term = 1.0 / (i*2+1) s += term * ((-1)**i) if term < 1e-6: break i += 1 print "%.6lf" % s
Python
from sys import stdin from decimal import * a, b, c = map(int, stdin.readline().strip().split()) getcontext().prec = c print Decimal(a) / Decimal(b)
Python