Python Forum
replace specific words in strings
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace specific words in strings
#1
How can I be able to do the following:

I have list of sentences and list of dictionaries.
I want to be able to replace each pair in a dictionary to 'NAME' to hilight the pair in the string.
For example: 'word P0 word P1 word P2 word' this sentence has 3 (P)s I want to choose (P0,P1) to be the first pair(so the sentence will be like this:'word NAME word NAME word OTHER word' then to choose (P0,P2) to be the second pair,(the sentence will be like this:'word NAME word OTHER word NAME word'), finally,(P1,P2) will be chosen to be the last pair('word OTHER word NAME word NAME word'.

If a sentence has a pair (P0,P0) where P0 = P0 then it is impossible to have pair with the same value so I will replace the pair to OTHER, for instance,word P0 word P0 word => will be word OTHER word OTHER word.
If a sentence has 3 (p)s 2 of them are equal then we need to replace one of them as OTHER.

For example: word word P0 word P0 word P1 word => will be word word OTHER word NAME word NAME word or word word NAME word OTHER word NAME word

S = [ ‘ word word word P0 word word P1 word’, 
      ‘ word word P0 word word P1 , P2 , P3, word word’,  
      ‘word word P0 word P0 word P1 word ’, 
      ‘word P0 word word word P0’]

P_dic = [{‘id’: s1 , ‘first_p’: p0, ‘second_p’ : p1},
{‘id’: s2 , ‘first_p’: p0, ‘second_p’ : p1},
{‘id’: s2 , ‘first_p’: p0, ‘second_p’ : p2},
{‘id’: s2 , ‘first_p’: p0, ‘second_p’ : p3},
{‘id’: s2 , ‘first_p’: p0, ‘second_p’ : p2},
{‘id’: s2 , ‘first_p’: p1, ‘second_p’ : p2},
{‘id’: s2 , ‘first_p’: p1, ‘second_p’ : p3},
{‘id’: s2 , ‘first_p’: p2, ‘second_p’ : p3},
{‘id’: s2 , ‘first_p’: p0, ‘second_p’ : p2}, 
{‘id’: s3 , ‘first_p’: p0, ‘second_p’ : p0}, 
{‘id’: s3 , ‘first_p’: p0, ‘second_p’ : p1},
{‘id’: s4 , ‘first_p’: p0, ‘second_p’ : p0}]]

def replace_word(s, word, replacement, n ):
   index = -1
   for _ in range(n):
       try:
           index = s.index(word, index + 1)
       except ValueError:
           return s
   return s[:index] + s[index:].replace(word, replacement, 1)

for i in S:
       for p in P_dic:
           for key,value in i.items():
               if  key == p['id']:
                   if p['first_p'].lower() != p['second_p'].lower():
                       v = p['first_p']
                       v2 = p['second_p']
                       s1 = ''.join(i[key])
                       v_count = s1.count(v)
                       v2_count = s1.count(v2)
                       s1 = replace_word(s1 ,v,'NAME',v_count)       
                       s1 = replace_nth(s1 ,v2 ,'NAME',v2_count)
The above code is my attempt but it does not work as I want. I do not know how can I replace other words in the dictionary to OTHER. Also, it just replace the last word in case of duplication.
I appreciate any help or hints.
Reply
#2
I'm not sure I understand what you are trying to do, and I'm not sure I understand your code. P0 and P1 are words in your strings, but then you are using p0 and p1 as undefined variable names in P_dic. You have an extra bracket at the end of the definition of P_dic. P_dic has duplicates in it. If you remove the id, which doesn't seem to serve a purpose, it has even more duplicates. You loop for i in S Since S is a list of strings, that means i is a string. But then you loop over for key, value in i.items(). But i is a string and strings don't have the items method.

If you want to replace the first instance of a word with NAME and the other instances with OTHER, you just need:

sentence = sentence.replace(word, 'NAME', maxsplit = 1)
sentence = sentence.replace(word, 'OTHER')
I would have all the replacement words and the pairs you want to NAME be lists. Then loop over the sets and words, replacing with NAME if in the pairs

replacements = ['P0', 'P1', 'P2', 'P3']
pairs = [['P0', 'P1'], ['P0', 'P2'], ['P1', 'P2], ...]
replaced = []
for sentence in S:
    for pair in pairs:
        for word in replacements:
            if word in pair:
                sentence.replace(word, 'NAME', maxsplit = 1)
            sentence.replace(word, 'OTHER')
        replaced.append(sentence)
That is untested, but should replace the first instance of each word in the pair with NAME, and all other p-words with OTHER. I'm not sure about your special cases because I'm not sure I understand them.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thank you for your answer. Sorry, I made a mistake ,S is a list of dictionaries isn't a flat list as in the question. Each dictionary in S has a key ==>' id of a sentence' and value ==> the sentence itself.
Reply
#4
Okay, that makes more sense. But you would just be looping over less pairs than in my example: just the ones where the id's match. The replacements would still work the same.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 756 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,754 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,790 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  read logfile between two specific strings FelixReiter 6 2,885 Jan-04-2021, 02:26 PM
Last Post: FelixReiter
  Trying to get unique words from a set of strings garam0 5 5,127 Apr-15-2020, 06:24 PM
Last Post: garam0
  Replace words in a file bitwo 3 2,424 Jan-22-2020, 04:05 PM
Last Post: bitwo
  Delete specific lines contain specific words mannyi 2 4,117 Nov-04-2019, 04:50 PM
Last Post: mannyi
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 3,455 Oct-17-2019, 03:04 PM
Last Post: baquerik
  Finding multiple strings between the two same strings Slither 1 2,511 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  Identify two specific words next to each stahorse 9 4,168 Apr-26-2019, 09:59 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020