Skip to content

Instantly share code, notes, and snippets.

@smeech
Created January 31, 2025 16:14
Show Gist options
  • Select an option

  • Save smeech/0538ec4c3d4e5a17a0935eaef5c14704 to your computer and use it in GitHub Desktop.

Select an option

Save smeech/0538ec4c3d4e5a17a0935eaef5c14704 to your computer and use it in GitHub Desktop.
[Contractions] Export smallest unique contractions of a list of words for Espanso #espanso #python
# Export smallest unique contractions of a list of words for Espanso
from collections import defaultdict
def shortest_unique_component(word, words_count):
if words_count is None:
return None
for i in range(len(word)):
contraction = word[:i+1]
if words_count[contraction] == 1:
return contraction
def process_words(file_name):
words_count = defaultdict(int)
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
for i in range(len(word)):
contraction = word[:i+1]
words_count[contraction] += 1
return words_count if words_count else None
def main():
file_name = input("Enter the file name containing the list of words: ")
words_count = process_words(file_name)
matches = []
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
contraction = shortest_unique_component(word, words_count)
if contraction is not None and contraction != word:
matches.append((contraction, word))
with open("contractions.yml", "w") as output_file:
output_file.write("matches:\n")
for contraction, word in matches:
output_file.write(f" - trigger: {contraction}\n")
output_file.write(f" replace: {word}\n")
if __name__ == "__main__":
main()
@smeech

smeech commented Jan 31, 2025

Copy link
Copy Markdown
Author

Takes a list of words and returns an Espanso .yml file containing trigger:/replace: pairs for those words that have unique contractions.

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