Last active
November 4, 2019 07:14
-
-
Save hackerb9/e7b8532c315f47438080eb469e717f2a to your computer and use it in GitHub Desktop.
Simplest example of parsing text files of ITIS taxonomy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# globals | |
name={} | |
hierarchy={} | |
vernacular={} | |
synonyms={} | |
def loaddb(): | |
"Load up databases into dictionaries: name, hierarchy, vernacular" | |
global name, hierarchy, vernacular, synonyms | |
# Slurp up conversion from taxonomic serial number x to longname y | |
f=open("longnames", "rb") | |
for line in f: | |
line=line.decode('latin-1') | |
(x,y) = line.split('|') | |
name[x]=y.rstrip() | |
f.close() | |
# Load in hierarchy, mapping taxonomic serial number n to hierarchy h | |
f=open("hierarchy", "rb") | |
for line in f: | |
line=line.decode('latin-1') | |
(h,n,*dummy) = line.split('|') | |
hierarchy[n]=h.rstrip() | |
f.close() | |
# Read in the vernacular database (mapping 'European frog' to '173444') | |
f=open("vernaculars", "rb") | |
for line in f: | |
line=line.decode('latin-1') | |
(n,v,*dummy) = line.split('|') | |
v=v.lower() | |
if v not in vernacular: | |
vernacular[v]=[] | |
vernacular[v].append(n) | |
f.close() | |
# Read in the synonyms database (mapping obsolete TSN to current TSN) | |
f=open("synonym_links", "rb") | |
for line in f: | |
line=line.decode('latin-1') | |
(n,s,dummy) = line.split('|') | |
synonyms[n]=s | |
f.close() | |
def printhierarchy(v): | |
# Look up by vernacular and print hierarchy | |
try: | |
vlist=vernacular[v.lower()] | |
# Print out the hierarchy | |
for n in vlist: | |
if n in hierarchy: | |
h=hierarchy[n] | |
elif n in synonyms: | |
h=hierarchy[synonyms[n]] | |
else: | |
return False | |
print( v + ':' ) | |
for level in h.split('-'): | |
print ( ' → ' + name[level] ) | |
except KeyError: | |
print( "‘"+v+"’ not found" ) | |
# Main | |
loaddb() | |
from sys import argv | |
arg=' '.join( [ str(x) for x in argv[1:] ] ) | |
printhierarchy(arg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment