Last active
May 7, 2019 07:58
-
-
Save nwg-piotr/3a916c761d29572d88e29e0a2d18c095 to your computer and use it in GitHub Desktop.
Python script to sorts the `names.txt` file containing lines like `Name Surname` alphabetically by Surname and write the result to the `names_sorted.txt` file.
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/env python | |
# _*_ coding: utf-8 _*_ | |
""" | |
This script sorts the `names.txt` file containing lines like `Name Surname` alphabetically by Surname | |
and writes result to the `names_sorted.txt` file. | |
""" | |
import sys | |
def main(): | |
""" | |
(Optional) arguments: input and output file name. | |
""" | |
file_in = sys.argv[1] if len(sys.argv) > 1 else 'names.txt' | |
file_out = sys.argv[2] if len(sys.argv) > 2 else 'names_sorted.txt' | |
input_text = "" | |
try: | |
f = open(file_in, "r") | |
input_text = f.read() | |
f.close() | |
except Exception as e: | |
print(e) | |
exit(0) | |
print("UNSORTED: \n") | |
print(input_text + "\n") | |
unsorted_lines = input_text.splitlines() | |
# Let's swap `Name Surname` to `Surname Name` order | |
swapped = [] | |
for line in unsorted_lines: | |
words = line.split() | |
swap(words) | |
swapped.append(" ".join(words)) | |
# sort by Surname | |
sorted_lines = sorted(swapped) | |
# Swap `Surname Name` back to `Name Surname` | |
unswapped = [] | |
for line in sorted_lines: | |
words = line.split() | |
swap(words) | |
unswapped.append(" ".join(words)) | |
print("SORTED: \n") | |
output = '\n'.join(unswapped) | |
print(output) | |
f = open(file_out, "w") | |
f.write(output) | |
f.close() | |
def swap(m_list): | |
tmp = m_list[0] | |
m_list[0] = m_list[1] | |
m_list[1] = tmp | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment