Home > Software engineering >  how to change certain letters in a wordlist (txt file with python)
how to change certain letters in a wordlist (txt file with python)

Time:10-29

i have a wordlist:here is an example (txt file) place lime nest land

i want to get this as an output in an apart txt file: pl@ce lim3 n3st l@nd

i want that the letters a get transformed in @ but i only want 1 change each word so "apart" becomes "ap@rt" and not "@p@rt".

this is my first time using stackoverflow so sorry if my writing is bad and i do not speak english very well. im also new to coding (python) so i might not understand all the code very well.

CodePudding user response:

Split input string into individual words, replace first instance of 'a' with '@' in each word. Append edited words to output string.

input = 'place lime nest land'
output = ''

input = input.split(' ')

for i in input:
    i = i.replace('a', '@', 1)
    i = i.replace('e', '3', 1)
    output  = i   ' '

print(output)  

Output:

@part pl@c3 lim3 n3st l@nd 

CodePudding user response:

With regular expressions you can do

import re
s1 = re.sub(r'a(?=[^a]*?\b)', '@', 'apart place lime nest land')
s2 = re.sub(r'e(?=[^e]*?\b)', '3', s1)
print(s2)

Using the solution from this question. We can combine it into a single expression:

subs = {'a': '@', 'e': '3'}
pattern = re.compile(r'a(?=[^a]*?\b)|e(?=[^e]*?\b)')
s = pattern.sub(lambda x: subs[x.group()], 'apart place lime nest land')

print(s)

Output:

ap@rt pl@c3 lim3 n3st l@nd

This replaces the last letter a and last letter e within a word.

CodePudding user response:

Input from file, output to file

This code read words from the file file1.txt and write the changed word on file2.txt:

with open('file1.txt') as f:
    with open('file2.txt', 'w') as f2:
        for word in f:
            word = word.replace("a", "@", 1)
            word = word.replace("e", "3", 1)
            f2.write(word)

This change only the first occurrance of a letter, so apart becomes @part.

CodePudding user response:

Reverse the string, replace first occurence, then reverse the string back. (Hardcoded)

print('apart place lime nest land'[::-1].replace('a', '@', 3).replace('e', '3',2)[::-1])
# ap@rt pl@ce lim3 n3st l@nd

CodePudding user response:

this may be a rough first draft and some assumptions were made but here is a shot at a function. Could be cleaned up alot. Good luck

def updt_text(s):
    # assumptions, string of text is seperated by spaces and there are no odd characters
    words = s.split()
    newwords = []
    
    dictChanges = {
        'a': '@',
        'e': '3',
    }
    
    for word in words:
        for k, v in dictChanges.items():
            if k in word:
                word = word.replace(k, v)
                break
        newwords.append(word)
    
    return newwords
  • Related