Skip to content

Instantly share code, notes, and snippets.

@jacoby
Created March 1, 2024 04:49
Show Gist options
  • Save jacoby/2f5f5a898cb2cc682e43ab20c740e930 to your computer and use it in GitHub Desktop.
Save jacoby/2f5f5a898cb2cc682e43ab20c740e930 to your computer and use it in GitHub Desktop.
Python test
#!/usr/bin/env python
from sys import argv
import os
def read_file (file):
if os.path.exists(file):
with open( file , "r") as f:
words = f.read()
f.closed
return words
def write_file ( file, words ):
with open(file, 'w') as file:
file.write("\n".join(words))
def compare_wordlists( words1, words2 ):
list1 = words1.splitlines()
list2 = words2.splitlines()
onlyleft = []
onlyright = []
for word in list1 + list2:
if word in list1 and word not in list2:
onlyleft.append(word)
if word in list2 and word not in list1:
onlyright.append(word)
return (onlyleft, onlyright)
def main ():
file1 = argv[1]
file2 = argv[2]
words1 = read_file( file1 )
words2 = read_file( file2 )
onlyleft, onlyright = compare_wordlists( words1, words2 )
write_file("python_first_only", onlyleft)
write_file("python_last_only", onlyright)
if __name__ == '__main__':
main()
@brianwisti
Copy link

brianwisti commented Mar 1, 2024

Key suggestions: try pathlib for gentler file handling, and take advantage of list comprehensions.

from pathlib import Path
from sys import argv

def load_words(filename):
   return Path(filename).read_text(encoding="utf-8").splitlines()

def main():
    words1, words2 = [load_words(arg) for arg in argv[1:]]
    comparison = {
        "python_first_only": [word for word in words1 if word not in words2],
        "python_second_only": [word for word in words2 if word not in words1],
    }

    for label, result in comparison.items():
        Path(label).write_text("\n".join(result), encoding="utf-8")

if __name__ == "__main__":
    main()

Also consider sets for your wordlist comparison, if you only want unique words from each.

def load_words(filename):
   return set(Path(filename).read_text(encoding="utf-8").splitlines())

def main():
    words1, words2 = [load_words(arg) for arg in argv[1:]]
    comparison = {
        "python_first_only": words1 - words2,
        "python_second_only": words2 - words1,
    }
    # ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment