Search code examples
pythonpython-itertools

How do I use itertools in Python to generate all possible variants of a list of keywords with leet code?


Python - How to make current script iterate through list of words instead of one string/word only?

I am very new to python, and have put together a script parsing different scripts i've looked at.

The goal is to return all possible variants of a list of keywords, replacing the characters by leet code (e.g.: 'L33T' or 'l337' instead of 'Leet')

I have been able to achieve this for one string/word only, but I wish to be able to input a list of keywords and obtain the same results.

This is my first time using Stack overflow, and I would really appreciate any help you can provide me :)

Here is my code:

import itertools

def leet(word):
    leet_matches = [['a','@','4','∆','Д','а','а','a','à'],
    ['b','8','b','ḃ','ḅ','ḇ'],
    ['c','<','{','[','(','©'],
    ['d','d','ď','ḋ','ḍ','ḏ','ḑ','ḓ'],
    ['e','3','£','₤','€','е'],
    ['f','7','ƒ','ḟ'],
    ['g','9','[','-','6','ĝ','ğ','ġ','ģ','ǧ','ǵ','ḡ'],
    ['h','4','#','ĥ','ȟ','ḣ','ḥ','ḧ','ḩ','ḫ','ẖ'],
    ['i','1','|','!','ì','í'],
    ['j','√','ĵ','ǰ'],
    ['k','ķ','ǩ','ḱ','ḳ','ḵ','ķ','ǩ','ḱ','ḳ','ḵ'],
    ['l','1','|','ĺ','ļ','ľ','ḷ','ḹ','ḻ','ḽ'],
    ['m','м','ḿ','ṁ','ṃ'],
    ['n','И','и','п','ñ','ń','ņ','ň','ǹ','ṅ','ṇ','ṉ','ṋ'],
    ['o','0','Ø','Θ','о','ө','ò','ó','ô','õ','ö','ō','ŏ','ő','ơ','ǒ','ǫ','ǭ'],
    ['p','р','ṕ','ṗ'],
    ['q','9','(',')','0'],
    ['r','Я','®','ŕ','ŗ','ř','ȑ','ȓ','ṙ','ṛ','ṝ','ṟ'],
    ['s','5','$','§','ś','ŝ','ş','š','ș','ṡ','ṣ','ṥ','ṧ','ṩ'],
    ['t','7','+','т','ţ','ť','ț','ṫ','ṭ','ṯ','ṱ','ẗ'],
    ['u','ù','ú','û','ü','ũ','ū','ŭ','ů','ű','ų','ư','ǔ','ǖ','ǘ'],
    ['v'],
    ['w','Ш','ŵ','ẁ','ẃ','ẅ','ẇ','ẉ','ẘ'],
    ['x','×','%','*','Ж','ẋ','ẍ'],
    ['y','¥','Ч','ү','у','ṽ'],
    ['z','5','ź','ż','ž','ẑ']]
    l = []
    for letter in word:
        for match in leet_matches:
            if match[0] == letter:
                l.append(match)
    return list(itertools.product(*l))

word = "hola"
test_list = leet(word)

def remove(string):
    return string.replace(" ", "")

res = [''.join(tups) for tups in test_list]
print (str(res)+remove(str(res)))


import csv
with open ('leet_latinalphabet.csv', mode ='w') as csvfile:
    fieldnames = ['leet variants']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({"leet variants":str(res)[1:-1].replace("'","")})

Solution

  • Loop over the list of words, calling leet() on each word.

    words = ['hola', 'some', 'other', 'word']
    
    with open ('leet_latinalphabet.csv', mode ='w') as csvfile:
        fieldnames = ['word', 'leet variants']
        writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
        writer.writeheader()
        for word in words:
            row = {"word": word, "leet variants": ",".join(leet(word))}
            writer.writerow(row)