Skip to content

Python NLTK #39

@alexanderdfox

Description

@alexanderdfox

import nltk
from nltk.corpus import words

Make sure you have the word list

#nltk.download('words')

word_list = [w.lower() for w in words.words() if w.isalpha()]

def collatz_sequence(n):
seq = [n]
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
return seq

def letter_to_number(letter):
return ord(letter.upper()) - 64 if letter.isalpha() else 0

def find_word(length):
"""Return the first word from the list with the given length."""
for w in word_list:
if len(w) == length:
return w
# fallback if no word found
return 'a' * length

def collatz_sentence(word):
sentence = []
for letter in word:
n = letter_to_number(letter)
seq = collatz_sequence(n)
for length in seq:
length = min(length, 12) # cap to reasonable word length
sentence.append(find_word(length))
return ' '.join(sentence)

Example usage

word = "Tell each who hears you to tell each who hears them to tell each who hears to"
sentence = collatz_sentence(word)
print(f"Original word: {word}")
print(f"Collatz sentence:\n{sentence}")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions