Skip to content

Instantly share code, notes, and snippets.

@russkel
Created February 27, 2025 06:15
Show Gist options
  • Save russkel/2164c5a817822e498c9c52364f03e2ac to your computer and use it in GitHub Desktop.
Save russkel/2164c5a817822e498c9c52364f03e2ac to your computer and use it in GitHub Desktop.
import hashlib
def read_wordnet_line(filename, line_number):
"""Reads a specific line from a file, wrapping around if necessary."""
try:
with open(filename, 'r') as f:
lines = f.readlines()
num_lines = len(lines)
if num_lines == 0:
return None # Handle empty file case
adjusted_line_number = (line_number - 1) % num_lines # Adjust to 0-based index and wrap around
return lines[adjusted_line_number].strip().split()
except FileNotFoundError:
return None
def process_string(input_string):
"""Hashes a string, splits the hash into two numbers, and reads lines from WordNet files."""
# Hash the input string using SHA256
sha256_hash = hashlib.sha256(input_string.encode('utf-8')).digest()
# Split the hash into two halves
half_length = len(sha256_hash) // 2
first_half = sha256_hash[:half_length]
second_half = sha256_hash[half_length:]
# Convert the halves to integers (using base 16)
try:
first_number = int.from_bytes(first_half, signed=False)
second_number = int.from_bytes(second_half, signed=False)
except ValueError:
return "Error: Could not convert hash halves to integers."
# Read lines from the WordNet files
adj_exc_line = read_wordnet_line('/usr/share/wordnet/adj.exc', first_number)[-1]
noun_exc_line = read_wordnet_line('/usr/share/wordnet/noun.exc', second_number)[-1]
return adj_exc_line, noun_exc_line
# Example usage:
if __name__ == "__main__":
import sys
input_string = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "example string"
print (f"Input string: {input_string}")
adj_line, noun_line = process_string(input_string)
if adj_line:
print(f"Line from adj.exc: {adj_line}")
else:
print("Could not read line from adj.exc (file not found or empty).")
if noun_line:
print(f"Line from noun.exc: {noun_line}")
else:
print("Could not read line from noun.exc (file not found or empty).")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment