def get_name(raw_name, this_dict): name = HumanName(raw_name) name.capitalize() this_dict['first_name'] = name.first this_dict['last_name'] = name.last this_dict['middle_name'] = name.middle this_dict['suffix'] = name.suffix
def getname(name): h = HumanName(name) h.capitalize() return { 'firstname': "%s %s" % (h.first, h.middle), 'lastname': "%s %s" % (h.last, h.suffix) }
def GetNameLink(name): # Finds and returns formatted name and wikilinks for given name. name = HumanName(name) name.capitalize(force=True) name = str(name) soup = GetSoup("https://en.wikipedia.org/wiki/" + name.replace(" ", "_"), False).text wikitext = name tennis = [ "International Tennis Federation", "Prize money", "Grand Slam", "tennis career", "Wikipedia does not have", "may refer to", "WTA", "ITF", "ATP" ] pipe = False if soup != None: if any([f in soup for f in tennis ]): # player article exists, or no article exists if "Redirected from" in soup: soup = GetSoup(soup, True) title = str(soup.title.string).replace(" - Wikipedia", "").strip() wikitext = title pipe = True # if name is redirect, pipes wikilink to avoid anachronist names, e.g. using "Margaret Court" instead of "Margaret Smith" before she married. else: # article exists for name but for different person wikitext = name + " (tennis)" pipe = True wikilink = "[[" + wikitext + ("|" + name if pipe else "") + "]]" split_name = name.split(" ") abbr_name = "-".join( f[0] for f in split_name[0].split("-")) + " " + " ".join( split_name[1:] ) # reduce name to first name initials + last name, e.g. "J-L Struff" abbr_wikilink = "[[" + wikitext + "|" + abbr_name + "]]" return [name, wikilink, abbr_wikilink]
def course_event_title_and_contact(course): try: section = get_sws_section(course) meeting = section.meetings[0] if hasattr(section, 'meetings') and len( section.meetings) else None instructor = meeting.instructors[0] if hasattr( meeting, 'instructors') and len(meeting.instructors) else None first_name = instructor.first_name if hasattr(instructor, 'first_name') else '' surname = instructor.surname if hasattr(instructor, 'surname') else '' uwnetid = instructor.uwnetid if hasattr(instructor, 'uwnetid') else '' email = instructor.email1 if hasattr(instructor, 'email1') else '' name = HumanName(' '.join([first_name, surname])) name.capitalize() except DataFailureException as err: if err.status == 404: section = None name = None email = None uwnetid = None else: raise return { 'title_long': section.course_title_long if section else '', 'name': '%s %s' % (name.first, name.last) if name else '', 'uwnetid': uwnetid if uwnetid else '', 'email': email if email and len(email) else "*****@*****.**" % uwnetid if uwnetid else '' }
def course_event_title_and_contact(course): try: section = get_sws_section(course) meeting = section.meetings[0] if hasattr( section, 'meetings') and len(section.meetings) else None instructor = meeting.instructors[0] if hasattr( meeting, 'instructors') and len(meeting.instructors) else None first_name = instructor.first_name if hasattr( instructor, 'first_name') else '' surname = instructor.surname if hasattr(instructor, 'surname') else '' uwnetid = instructor.uwnetid if hasattr(instructor, 'uwnetid') else '' email = instructor.email1 if hasattr(instructor, 'email1') else '' name = HumanName(' '.join([first_name, surname])) name.capitalize() except DataFailureException as err: if err.status == 404: section = None name = None email = None uwnetid = None else: raise return { 'title_long': section.course_title_long if section else '', 'name': '%s %s' % (name.first, name.last) if name else '', 'uwnetid': uwnetid if uwnetid else '', 'email': email if email and len(email) else "*****@*****.**" % uwnetid if uwnetid else '' }
def normalize_name(first_name, last_name): """Normalizes capitalization of first and last name.""" name = HumanName() name.first = first_name name.last = last_name name.capitalize() return (name.first, name.last)
def clean_authors(authors): cleaned_authors = [] authors = authors.lower() # get rid of commas where there are suffixes, like Jr. or III authors = authors.replace(", jr.", " jr.") authors = authors.replace(", iii", " iii") authors = authors.replace(", ph.d", "") # special cases authors = authors.replace("organizer:", "") authors = authors.replace("roel m,", "roel m.") if authors == 'kozue miyashiro, etsuko harada, t.': author_list = ['kozue miyashiro', 'etsuko harada, t.'] else: author_list = authors.split(",") for author in author_list: author = HumanName(author.lower()) if author.first == '' or author.last == '': raise ValueError("invalid author name: {}".format(author)) author.capitalize() author.string_format = u"{last}, {title} {first} {middle}, {suffix}" cleaned_authors.append(unicode(author)) return cleaned_authors
def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from medusa_website.users.models import MemberRecord, User # Uses medusa_website.users.validators.CustomSignupEmailValidator user: User = super().save_user(request, user, form, commit=True) # Try to get first and last name's from MemberRecords # A member record should already have been verified to exist using the custom_email_validators try: member_record = MemberRecord.objects.get(email=user.email) user.is_member = True user.create_member_id() user.membership_expiry = member_record.end_date member_name = HumanName(member_record.name) member_name.capitalize(force=True) user.name = member_name except MemberRecord.DoesNotExist: logger.warning(f"Member Record for {user.email} does not exist") user_part, domain_part = user.email.rsplit("@", 1) if domain_part == "medusa.org.au": user.is_medusa = True user.is_member = False user.is_staff = True if commit: user.save() return user
def simplify_name(official_name): try: simplified = HumanName(official_name.strip().lower()) simplified.capitalize() except UnicodeDecodeError: simplified = official_name return str(simplified)
def parse(name): try: parsed_name = HumanName(name) parsed_name.capitalize(force=True) return jsonify(parsed_name.as_dict()) except Exception as e: return jsonify(str(e))
def caplastname(dataset): for i in range(0, len(dataset['Last Name'])): n = str(dataset['Last Name'][i]) name = HumanName(n) name.capitalize(force=True) ln = name.first dataset['Last Name'][i] = ln return dataset
def extract_name(full_name): full_name = full_name.strip() name = HumanName(full_name) name.capitalize() first_name = " ".join(list(filter(None, [name.title, name.first]))) last_name = name.last first_and_last_name = " ".join([first_name, last_name]) return first_and_last_name, first_name, last_name
def get_full_name(person): if (len(person.display_name) > 0 and not person.display_name.isdigit() and not person.display_name.isupper()): return person.display_name name = HumanName(person.full_name) name.capitalize() name.string_format = "{first} {last}" return str(name)
def parse_name(item): """ Parses a name string into an Author object. :param item: String containing author name and possibly email :return: Author """ # Find emails from regex email_group = emailRegex.search(item) email = None # If emails found, take first email if email_group: email = email_group.group(0) # Remove email from string item = emailWithBracketsRegex.sub("", item) # Remove prefixes from string item = prefixRegex.sub("", item) # Remove suffixes from string item = suffixRegex.sub("", item) # Remove words in brackets () if words exist outside brackets if not bracketRegex.fullmatch(item): item = bracketRegex.sub(" ", item) # Strip extraneous characters from string item = item.strip(strip_chars) # Parse remaining string with HumanNameParser to find name name = HumanName(item) if not name.full_name: app.logger.warning( "Unable to parse name string %s: no full_name returned in name %s", item, name, ) return None # Only force capitalization of names with mixed capitalization above certain percentage name.capitalize(force=force_capitalization(name.full_name)) author = Author() if name.first: author.givenname = name.first if name.last: author.familyname = name.last if name.middle: author.middlename = name.middle if email: author.email = email if not name.first and not name.last: author.name = name.full_name else: author.create_full_name() return author
def set_name_from_memberlist(modeladmin, request, queryset: QuerySet[User]): for user in queryset: try: member_record = MemberRecord.objects.get(email=user.email) member_name = HumanName(member_record.name) member_name.capitalize(force=True) user.name = member_name user.save() except MemberRecord.DoesNotExist: pass
def names_match(a, b): name_a = HumanName(a) name_b = HumanName(b) name_a.capitalize(force=True) name_b.capitalize(force=True) if name_a.first == name_b.first and name_a.last == name_b.last: return True else: return False
def get_display_name(self): if self.has_display_name(): return self.display_name if self.has_first_name(): name = HumanName("%s %s" % (self.first_name, self.last_name)) else: name = HumanName(self.last_name) name.capitalize() name.string_format = "{first} {last}" return str(name)
def display_full_name_with_correct_capitalization(full_name): """ See documentation here: https://github.com/derek73/python-nameparser :param full_name: :return: """ full_name.strip() full_name_parsed = HumanName(full_name) full_name_parsed.capitalize() full_name_capitalized = str(full_name_parsed) return full_name_capitalized
def name_transform(licensee: dict): if licensee.setdefault('fullname', '') != '': fullname = HumanName(licensee['fullname']) fullname.capitalize() licensee['fullname'] = str.title(getattr(fullname, 'full_name')) licensee['firstname'] = getattr(fullname, 'first', '') licensee['middlename'] = getattr(fullname, 'middle', '') licensee['lastname'] = getattr(fullname, 'last', '') else: licensee['firstname'] = str.title(licensee['firstname']) licensee['middlename'] = str.title(licensee['firstname']) licensee['lastname'] = str.title(licensee['lastname']) return licensee
def _massage_payload(self, payload): for k, v in payload.items(): if pd.isnull(v) or not v: # Replace nan or None with empty string. payload[k] = "" # Ensure names aren't all caps or all lowercase. if payload.get("firstname") and payload.get("lastname"): name = HumanName() name.first = payload["firstname"] name.last = payload["lastname"] name.capitalize() payload["firstname"] = name.first payload["lastname"] = name.last
def user_fullname(user): if hasattr(user, 'display_name'): if ((user.display_name is None or not len(user.display_name) or user.display_name.isupper()) and hasattr(user, 'first_name')): fullname = HumanName('%s %s' % (user.first_name, user.surname)) fullname.capitalize() fullname.string_format = '{first} {last}' return str(fullname) else: return user.display_name elif hasattr(user, 'email'): return user.email.split('@')[0] # CanvasUser else: raise UserPolicyException('Invalid user')
def create_payload(donor): payld = {} payld['phone_number'] = donor['phone_number'] payld['email'] = donor['email'] payld['postal_code'] = donor['zip'] name = HumanName(donor['firstname'] + " " + donor['lastname']) name.capitalize() payld['first_name'] = name.first payld['last_name'] = name.last payld['city'] = donor['city'] payld['state'] = donor['state'] payld['country'] = COUNTRYS_TO_ABBREV[donor['country']] payld['street1'] = donor['addr1'] payld['opt_in_path_id'] = OPT_IN_PATH_ID return payld
def catogorize_by_instructor(data): instructorsDict = {} for fce in data: if 'instructor' in fce and len(fce['instructor']) > 2: name = HumanName(fce['instructor']) name.capitalize() instructor = "{} {}".format(name.first, name.last).strip() if len(instructor) > 2: course = Course(fce) if instructor in instructorsDict: instructorsDict[instructor]['courses'].append(course) else: instructorsDict[instructor] = Instructor(str(name)) instructorsDict[instructor]['courses'].append(course) return instructorsDict
def standardize(res): # Standardize name name = HumanName(res['list_name']) name.capitalize() res['list_name'] = str(name) if 'detail_name' in res: dname = HumanName(res['detail_name']) dname.capitalize() res['detail_name'] = str(dname) # Lowercase email if 'list_email' in res: res['list_email'] = res['list_email'].lower() # Remove `Faculty - ` from affiliation res['list_affiliation'] = res['list_affiliation'].replace('Faculty - ', '') return res
def get_dblp_key(authors, year): if isinstance(authors, str): authors = [authors] # start with first author's full name key = HumanName(authors[0]).last key = key.capitalize() # e.g. de Val key = key.replace(' ', '') key = key.replace('-', '') key = key.replace('ß', 'ss') key = key.replace('ä', 'ae') key = key.replace('ö', 'oe') key = key.replace('ü', 'ue') # append co-authors' first letter from name for au in authors[1:]: cur_author = HumanName(au) key += cur_author.last[0] # add year key += str(year)[2:] key = unicodedata.normalize('NFKD', key).encode('ascii', 'ignore').decode() return str(key)
def standardize(res): # Standardize name name = HumanName(res['list_name']) name.capitalize() res['list_name'] = str(name) if 'detail_name' in res: dname = HumanName(res['detail_name']) dname.capitalize() res['detail_name'] = str(dname) # Lowercase email if 'list_email' in res: res['list_email'] = res['list_email'].lower() # Remove `Faculty - ` from affiliation res['list_affiliation'] = res['list_affiliation'].replace( 'Faculty - ', '') return res
def initContact(contactId: str): assert contactId not in activeContacts activeContacts.add(contactId) contact = dir.getContact(contactId) contactsToEmails[contactId] = contact['email'] name = " ".join( filter(None, [ contact.get('title_before_name'), contact.get('first_name'), contact.get('last_name'), contact.get('title_after_name') ])) #name = name.translate(str.maketrans('', '', string.punctuation)) name = name.translate(str.maketrans('', '', '@')) name = HumanName(name.lower().strip()) name.capitalize() if re.search('^(\w\.)+$', name.first): name.first = name.first.upper() contactsToNames[contactId] = name.__str__()
def respond(self, conversation, message): # parse name name = HumanName(message) name.capitalize(force=True) if name.middle: first_name = "{0} {1}".format(name.first, name.middle) else: first_name = name.first last_name = name.last # update conversation object conversation.raw_name = message conversation.first_name = first_name conversation.last_name = last_name conversation.save() # advance to next stage from rbot.stages import postal_code return (postal_code.Stage(), None)
def parse_name(self, name_raw): """ Parses a raw_name, e.g. "Corbato, F.J." into first, middle, and last name >>> p=Person(name_raw='Corbato, F.J.') >>> p.last, p.first, p.middle ('Corbató', 'F', 'J') :param name_raw: :return: """ # fix names like "Verzuh M., F.", where the middle name comes after the last name # -> it should be Verzuh, F. M. match = re.match('([A-Z][a-z]+) ([A-Z])\., ([A-Z][a-z]*)\.*', name_raw) if match: name_raw = f'{match.groups()[0]}, {match.groups()[2]}. {match.groups()[1]}.' name = HumanName(name_raw) # If first and middle initials have periods but not spaces -> separate, e.g. "R.K. Teague" if re.match('[a-zA-Z]\.[a-zA-Z]\.', name.first): name.middle = name.first[2] name.first = name.first[0] # Capitalize after splitting joined initials, otherwise R.K. becomes R.k. (i.e. middle # inital is interpreted as lower case) name.capitalize(force=True) name.last = name.last name.first = name.first.strip('.') name.middle = name.middle.strip('.') last_name_replacements = [('Corbato', 'Corbató'), ('Corbatò', 'Corbató'), ('Verguh', 'Verzuh')] for replacement in last_name_replacements: name.last = name.last.replace(replacement[0], replacement[1]) return name.last, name.first, name.middle
def GetNameLink(name, country): # Finds and returns formatted name and wikilinks for given name. name = HumanName(name) name.capitalize(force=True) name = str(name) soup = GetSoup("https://de.wikipedia.org/wiki/" + name.replace(" ", "_"), False).text wikitext = name tennis = [ "International Tennis Federation", "Preisgeld", "Grand Slam", "Tenniskarriere", "Diese Seite existiert nicht", "ist der Name folgender Personen", "WTA", "ITF", "ATP" ] pipe = False if soup != None: if any([f in soup for f in tennis ]): # player article exists, or no article exists if "Weitergeleitet von" in soup: soup = GetSoup(soup, True) title = str(soup.title.string).replace( " - Wikipedia", "").replace(" – Wikipedia", "").strip() if len(title.split(" ")) >= 3 and country == "RUS": title = title.split(" ") title = title[0] + " " + " ".join(title[2:]) wikitext = title pipe = False # If True, then if name is redirect, pipes wikilink to avoid anachronist names, e.g. using "Margaret Court" instead of "Margaret Smith" before she married. else: # article exists for name but for different person wikitext = name + " (Tennisspieler)" pipe = True wikilink = ("Ziel=" if not pipe else "") + wikitext + ("|" + name if pipe else "") split_name = wikitext.replace(" (Tennisspieler)", "").split(" ") abbr_name = ".-".join( f[0] for f in split_name[0].split("-") ) + ". " + " ".join( split_name[1:] ) # reduce name to first name initials + last name, e.g. "J.-L. Struff" abbr_wikilink = wikitext + "|" + abbr_name return [name, wikilink, abbr_wikilink]
def attendee_user(attendee): """ Return a user record for the attendee, if non exists create a new one """ # Check if they are a user try: user = User.objects.get(email=attendee['email']) # If not create a new user except User.DoesNotExist: # Create a temporary password and username which is 30 chars max password = '******' # brightmap backwards username = attendee['email'][0:30] try: user = User.objects.create_user(username=username, email=attendee['email'], password=password) except Exception, error: message = "Exception creating user:" + str(error) print message logger.error(message) return None name = attendee['first_name'].strip( ) + ' ' + attendee['last_name'].rstrip() try: name = HumanName(name) name.capitalize() except: user.first_name = attendee['first_name'].strip().capitalize() user.last_name = attendee['last_name'].rstrip().capitalize() else: user.first_name = name.first.capitalize() user.last_name = name.last.capitalize() user.save() profile = Profile(user=user) profile.save()
def clean_names(): users = User.objects.all() for user in users: if not user.first_name: continue name = user.first_name + ' ' + user.last_name try: name = HumanName(name) except Exception, e: continue name.capitalize() if name.middle: pass user.first_name = name.first.capitalize() user.last_name = name.last.capitalize() print unicode(name) + ':' + user.first_name + ',' + user.last_name try: user.save() except: pass
def normalize_candidate(text: str) -> str: if "\n" in text: log.debug(f"Handling running mate: {text}") text1, text2 = text.split("\n") name1 = HumanName(text1.strip()) name2 = HumanName(text2.strip()) name1.capitalize() name2.capitalize() if " of " in str(name2): log.debug(f"Skipped non-person running mate: {name2}") return str(name1) return str(name1) + " & " + str(name2) name = HumanName(text.strip()) name.capitalize() return str(name)
def namer(field): #pre if type(field) == tuple: w_name = re.sub('[\t\r\n]', '', ", ".join([x.encode('ascii', 'ignore') for x in field])).upper() else: w_name = re.sub('[\t\r\n]', '', field.encode('ascii', 'ignore')).upper() if 'ANONYMOUS' not in w_name: if ' FORMER ' not in w_name: w_name = re.split(";", w_name)[0] else: w_name = re.split(";", w_name)[1] w_name = re.sub("(?<=[`'/+]) | (?=['`/+])", '', w_name) #6A, 4A-C out = HumanName(w_name) out.middle = re.sub("^[A-Z] |^[A-Z]\. ", '', out.middle) if " " in out.last: out.last = re.sub("^[A-Z] |^[A-Z]\. ", '', out.last) if re.sub("^[A-Z]\.|^[A-Z]", '', out.first) == '' and len(out.middle) != 0: out.first, out.middle = out.middle, "" else: out.first = re.sub("^[A-Z] |^[A-Z]\. ", '', out.first) #post if out.middle.startswith("FOR ") or out.middle.startswith("- "): #7A, 1B, 3E out.middle = "" if " FOR " in out.last: out.last = re.sub(" FOR .*", '', out.last) if len(out.last) == 0 and len(out.title) != 0: #9A if " " in out.first: out = HumanName(out.first) else: out.first, out.last = "", out.first if " AND " in out.middle or " & " in out.middle: out.last = re.split("( AND )|( & )", out.middle)[0] out.middle = "" if "AND" in out.last or "&" in out.last: if out.last.startswith("AND ") or out.last.startswith("& "): #3F out.last = HumanName(out.last).last elif " AND " in out.last or " & " in out.last: out.last = re.sub("( AND ).*|( & ).*", '', out.last) out.first = re.split("( AND )|&|/|\+", out.first)[0] out.last = re.split("/", out.last)[0].strip() if len(re.sub("[^A-Z]", '', out.first)) == 1 and " " in out.last: out.first = out.last.split(" ")[0] out.last = out.last.split(" ")[1] out.capitalize() first, last = out.first, out.last if len(out.middle) > 0: if re.sub("^[A-Z]\.|^[A-Z]", '', out.middle) == '': out.middle = "" elif first.endswith("-") or out.middle.startswith("-"): first += out.middle else: first += " %s" % out.middle #8A-B if len(out.suffix) > 0: last += " %s" % out.suffix #2A return (first, last) else: name = HumanName(w_name) return (name.first, name.last)
class ParsedName(object): """Class for representing a name. After construction, the instance exposes the fields exposed by `HumanName` instance, i.e. `title`, `first`, `middle`, `last`, `suffix`. """ constants = _prepare_nameparser_constants() """The default constants configuration for `HumanName` to use for parsing all names.""" def __init__(self, name, constants=None): """Create a ParsedName instance. Args: name (str): The name to be parsed (must be non empty nor None). constants (:class:`nameparser.config.Constants`): Configuration for `HumanName` instantiation. (Can be None, if provided it overwrites the default one generated in :method:`prepare_nameparser_constants`.) """ if not constants: constants = ParsedName.constants self._parsed_name = HumanName(name, constants=constants) self._parsed_name.capitalize() def __iter__(self): return self._parsed_name def __len__(self): return len(self._parsed_name) def __repr__(self): return repr(self._parsed_name) def __str__(self): return str(self._parsed_name) @property def title(self): return self._parsed_name.title @property def first(self): return self._parsed_name.first @property def first_list(self): return self._parsed_name.first_list @property def middle(self): return self._parsed_name.middle @property def middle_list(self): return self._parsed_name.middle_list @property def last(self): return self._parsed_name.last @property def last_list(self): return self._parsed_name.last_list @property def suffix(self): return self._parsed_name.suffix @property def suffix_list(self): return self._parsed_name.suffix_list @classmethod def loads(cls, name): """Load a parsed name from a string. Raises: TypeError: when name isn't a type of `six.string_types`. ValueError: when name is empty or None. """ if not isinstance(name, six.string_types): raise TypeError( u'arguments to {classname} must be of type {string_types}'. format(classname=cls.__name__, string_types=repr(six.string_types))) if not name or name.isspace(): raise ValueError('name must not be empty') return cls(name) def dumps(self): """Dump the name to string, after normalizing it.""" def _is_initial(author_name): return len(author_name) == 1 or u'.' in author_name def _ensure_dotted_initials(author_name): if _is_initial(author_name) \ and u'.' not in author_name: seq = (author_name, u'.') author_name = u''.join(seq) return author_name def _ensure_dotted_suffixes(author_suffix): if u'.' not in author_suffix: seq = (author_suffix, u'.') author_suffix = u''.join(seq) return author_suffix def _is_roman_numeral(suffix): """Controls that the user's input only contains valid roman numerals""" valid_roman_numerals = [ u'M', u'D', u'C', u'L', u'X', u'V', u'I', u'(', u')' ] return all(letters in valid_roman_numerals for letters in suffix.upper()) # Create first and middle first_name = _ensure_dotted_initials(self.first) middle_name = _ensure_dotted_initials(self.middle) if _is_initial(first_name) and _is_initial(middle_name): normalized_names = u'{first_name}{middle_name}' else: normalized_names = u'{first_name} {middle_name}' normalized_names = normalized_names.format( first_name=first_name, middle_name=middle_name, ) if _is_roman_numeral(self.suffix): suffix = self.suffix.upper() else: suffix = _ensure_dotted_suffixes(self.suffix) final_name = u', '.join(part for part in (self.last, normalized_names.strip(), suffix) if part) # Replace unicode curly apostrophe to normal apostrophe. final_name = final_name.replace(u'’', '\'') return final_name
def clean_cognome(self): cognome = HumanName(self.cleaned_data['cognome']) cognome.capitalize( ) # senza force=true si ottiene Macchi invece di MacChi return cognome
def clean_nome( self ): # metodo per normalizzare automaticamente l'input nella forma Xxxxxx nome = HumanName(self.cleaned_data['nome']) nome.capitalize(force=True) return nome
def clean_name(self): name = self.cleaned_data['name'].lower() name = HumanName(name) name.capitalize() return unicode(name)
def ProcessScan(self, evt): print "Got a scan!" try: license = self.parser.decode(evt.data) except aamva.ReadError as e: #GUI interaction must be done in a thread-safe way wx.CallAfter(self.ErrorMessage, 'Invalid data.\n{0}'.format(e)) return name = HumanName("{} {}".format(xstr(license['first']).lower(), xstr(license['last']).lower())) name.capitalize() query = { 'firstName' : name.first, 'lastName' : name.last, 'address1' : license['address'], 'address2' : xstr(license['address2']), 'city' : license['city'], 'state' : license['state'], 'postalCode' : xstr(license['ZIP'])[0:5]+"-"+xstr(license['ZIP'])[5:], 'country' : license['country'], 'birthdate' : license['dob'] } params = urllib.urlencode(query) if license['expiry'] <= date.today(): wx.CallAfter(self.InfoMessage, str('ID expired {}'.format(license['expiry']))) webbrowser.open(BASE_URL + "?" + params, new=0, autoraise=False) else: webbrowser.open(BASE_URL + "?" + params, new=0, autoraise=True) #clear form self.clearForm() #set the fields self.NameText.SetValue(license['first']) if license['middle'] is not None: self.MiddleText.SetValue(license['middle']) self.SurnameText.SetValue(license['last']) self.DOBText.SetValue(xstr(license['dob'])) self.AddressText.SetValue(license['address']) self.Address2Text.SetValue(xstr(license['address2'])) self.CityText.SetValue(license['city']) self.StateText.SetValue(license['state']) self.ZIPText.SetValue(xstr(license['ZIP'])[0:5]+"-"+xstr(license['ZIP'])[5:]) self.IINText.SetValue(license['IIN']) self.LicenseNoText.SetValue(license['license_number']) self.IssuedText.SetValue(xstr(license['issued'])) self.ExpiresText.SetValue(xstr(license['expiry'])) try: self.CountryText.SetValue(license['country']) except KeyError: self.CountryText.SetValue("???") if license['sex'] == aamva.MALE: self.MaleRadio.SetValue(True) elif license['sex'] == aamva.FEMALE: self.FemaleRadio.SetValue(True) self.HeightText.SetValue(xstr(license['height'])) self.WeightText.SetValue(xstr(license['weight'])) if license['hair'] is None: self.HairText.SetValue("???") else: self.HairText.SetValue(license['hair']) if license['eyes'] is None: self.EyesText.SetValue("???") else: self.EyesText.SetValue(license['eyes']) self.EndorsementsText.SetValue(license['endorsements']) self.RestrictionsText.SetValue(license['restrictions'])
def ProcessScan(self, evt): print("Got a scan!") try: license = self.parser.decode(evt.data) except aamva.ReadError as e: #GUI interaction must be done in a thread-safe way wx.CallAfter(self.ErrorMessage, 'Invalid data.\n{0}'.format(e)) return name = HumanName("{} {}".format( xstr(license['first']).lower(), xstr(license['last']).lower())) name.capitalize() query = { 'firstName': name.first, 'lastName': name.last, 'address1': license['address'], 'address2': xstr(license['address2']), 'city': license['city'], 'state': license['state'], 'postalCode': xstr(license['ZIP'])[0:5] + "-" + xstr(license['ZIP'])[5:], 'country': license['country'], 'birthdate': license['dob'] } params = urllib.urlencode(query) if license['expiry'] <= date.today(): wx.CallAfter(self.InfoMessage, str('ID expired {}'.format(license['expiry']))) webbrowser.open(BASE_URL + "?" + params, new=0, autoraise=False) else: webbrowser.open(BASE_URL + "?" + params, new=0, autoraise=True) #clear form self.clearForm() #set the fields self.NameText.SetValue(license['first']) if license['middle'] is not None: self.MiddleText.SetValue(license['middle']) self.SurnameText.SetValue(license['last']) self.DOBText.SetValue(xstr(license['dob'])) self.AddressText.SetValue(license['address']) self.Address2Text.SetValue(xstr(license['address2'])) self.CityText.SetValue(license['city']) self.StateText.SetValue(license['state']) self.ZIPText.SetValue( xstr(license['ZIP'])[0:5] + "-" + xstr(license['ZIP'])[5:]) self.IINText.SetValue(license['IIN']) self.LicenseNoText.SetValue(license['license_number']) self.IssuedText.SetValue(xstr(license['issued'])) self.ExpiresText.SetValue(xstr(license['expiry'])) try: self.CountryText.SetValue(license['country']) except KeyError: self.CountryText.SetValue("???") if license['sex'] == aamva.MALE: self.MaleRadio.SetValue(True) elif license['sex'] == aamva.FEMALE: self.FemaleRadio.SetValue(True) self.HeightText.SetValue(xstr(license['height'])) self.WeightText.SetValue(xstr(license['weight'])) if license['hair'] is None: self.HairText.SetValue("???") else: self.HairText.SetValue(license['hair']) if license['eyes'] is None: self.EyesText.SetValue("???") else: self.EyesText.SetValue(license['eyes']) self.EndorsementsText.SetValue(license['endorsements']) self.RestrictionsText.SetValue(license['restrictions'])
def test123(self): hn = HumanName('Shirley Maclaine') hn.capitalize() self.m(str(hn), 'Shirley Maclaine', hn)
def test_capitalize_diacritics(self): hn = HumanName(u'matth\xe4us schmidt') hn.capitalize() self.m(unicode(hn), u'Matth\xe4us Schmidt', hn)
def test_capitalization_exception_for_III(self): hn = HumanName('juan q. xavier velasquez y garcia iii') hn.capitalize() self.m(str(hn), 'Juan Q. Xavier Velasquez y Garcia III', hn)
def test_capitalization_with_Mac_as_hyphenated_names(self): hn = HumanName('donovan mcnabb-smith') hn.capitalize() self.m(str(hn), 'Donovan McNabb-Smith', hn)
def test_capitalize_title(self): hn = HumanName('lt. gen. john a. kenneth doe iv') hn.capitalize() self.m(str(hn), 'Lt. Gen. John A. Kenneth Doe IV', hn)
def parse_name(name): parsed = HumanName(name) capitalize = request.args.get("capitalize", False) if capitalize and capitalize == "true": parsed.capitalize() return jsonify(parsed.as_dict())
def display_name(first_name, surname, reverse=False): name = HumanName("%s %s" % (first_name, surname)) name.capitalize() name.string_format = "{last}, {first}" if ( reverse is True) else "{first} {last}" return unicode(name)