Skip to content

Instantly share code, notes, and snippets.

@altanner
Last active August 1, 2022 19:20
Show Gist options
  • Save altanner/c08759652d84af879ee4024e4848eb4e to your computer and use it in GitHub Desktop.
Save altanner/c08759652d84af879ee4024e4848eb4e to your computer and use it in GitHub Desktop.
#~ standard library imports
import sys
import re
#~ local file import (the dict of codes:species)
try:
import species_dict
except Exception as e:
print(f"You'll need your codes:species dict here, named \"species_dict.py\"\n"
f"or there is an issue: {e}")
sys.exit(1)
#~ check for arg (the file to convert)
if len(sys.argv) != 2:
print("Please provide a file to convert, for example:")
print("python renamer.py tree1")
sys.exit(1)
#~ open the file, call it "infile"
with open(sys.argv[1]) as infile:
#~ read the lines into a variable called "newick"
newick = infile.read()
#~ create hit counter
hits = 0
for code in species_dict.spec_dict:
#~ check if code exists in tree
if re.search(code, newick):
#~ if so, replace code with species
newick = re.sub(code, species_dict.spec_dict[code], newick)
hits += 1 #~ increment counter
#~ make an output file to write to, prefix name with "renamed_"
with open(f"renamed_{sys.argv[1]}", "w") as outfile:
outfile.write(newick)
print(f"OK, {hits} nodes renamed in {sys.argv[1]}, written to renamed_{sys.argv[1]}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment