Home > database >  Loading a string line by line and replacing it using a dictionary - Python
Loading a string line by line and replacing it using a dictionary - Python

Time:06-12

I'm working on replacing a string using a dictionary.

Substituting with a dictionary is easy, but when replacing all words with the same word, the sentence becomes awkward.

So, I tried to read one line at a time and replace it once, but it failed.

# A function that randomly replaces a word
def ttc(*arg):
    a = random.choice([*arg])
    return ''.join(a)

text = """
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

"""
a_dic = {'working': ttc('tttttt', 'yyyyy', 'iiiiii'),
         'using': ttc('qqqq', 'eeeee', 'rrrrrr'),
         'on': ttc('cdcd', 'vvvdvdvv', 'dvd')
         }

new_list = []
pos = -1
for s in text.split("\n"):
    pos  = 1
    if s == "":
        new_list.append(s)
    else:
        for key in a_dic.keys():
            s = s.replace(key, a_dic[key])
            if pos == len(a_dic) - 1:
                new_list.append(s)


for d in new_list:
    print(d)

When performing random string substitution using a dictionary, can you replace several same words with different words? The result I want is below

text = """
I'm tttttt dvd replacing a string eeeee a dictionary.

I'm yyyyy cdcd replacing a string qqqq a dictionary.

I'm tttttt cdcd replacing a string qqqq a dictionary.
I'm tttttt vvvdvdvv replacing a string eeeee a dictionary.

I'm iiiiii cdcd replacing a string rrrrrr a dictionary.
I'm iiiiii vvvdvdvv replacing a string qqqq a dictionary.

"""

Help

CodePudding user response:

I'm not sure why you need the ttc function since choice already choose an element (string) in your list. So you don't need to join the result.

You can set your dictionary values to functions and use them as replacement in re.sub:

import re

a_dic = {'working': lambda x: random.choice(['tttttt', 'yyyyy', 'iiiiii']),
         'using': lambda x: random.choice(['qqqq', 'eeeee', 'rrrrrr']),
         'on': lambda x: random.choice(['cdcd', 'vvvdvdvv', 'dvd'])
         }

changed_text = text
for k in a_dic:
  changed_text = re.sub(rf'(?<=\W){k}(?=\W)', a_dic[k], changed_text)

print(changed_text)

Output:

I'm tttttt dvd replacing a string eeeee a dictionary.

I'm yyyyy cdcd replacing a string qqqq a dictionary.

I'm yyyyy cdcd replacing a string qqqq a dictionary.
I'm tttttt vvvdvdvv replacing a string eeeee a dictionary. cdcd

I'm yyyyy dvd replacing a string eeeee a dictionary.
I'm tttttt vvvdvdvv replacing a string qqqq a dictionary.
Edit:

You can also create a 'meta' function to avoid looping over the dictionary:

def replace_fun(match_obj):
  word = match_obj.group(0)
  if word in a_dic:
    return a_dic[word](word)
  else:
    return word

changed_text = re.sub(r'\w ', replace_fun, text)
  • Related