Eagle
Eagle

Reputation: 1197

Python - replace a word multiple times

Question: I have a case where I need to replace the words in a sentence with a dc every time the words in the sentence change. The sentence is:

Sweet Bad No No Long Yes Bike No Yes

Over the next few times the sentence will keep changing to:

Sweet Bad No No Long Yes Bike Yes No

Sweet Bad No No Short Yes Car Yes No

So, the output should look like:

Sweet Bad No No dc Yes dc dc dc

I want to replace the first instance of a change, from the first sentence to the next, with a dc. I wrote a piece of code but it does not seem right. Where am I going wrong?

 dont_care = "dc"
 hyp_curr = []
 hyp_next = []

 def create_hypothesis(stVal):
      splitVal = stVal.split()
      global hyp_curr
      global hyp_next

      if not hyp_curr: 
           hyp_curr = (' '.join(w for w in splitVal if w not in hyp_curr))
           return hyp_curr
      else: 
           hyp_next = splitVal
           print hyp_curr
           print hyp_next

           for wordc in hyp_curr.split():
                for wordn in hyp_next:
                     if hash(wordc) != hash(wordn):
                          hyp_curr = hyp_curr.replace(wordn,dont_care)
                          return hyp_curr

Upvotes: 1

Views: 424

Answers (2)

dstromberg
dstromberg

Reputation: 7177

Perhaps like this?

#!/usr/local/cpython-3.3/bin/python

import pprint

def rep_dc(list_):
    result = []
    for sublist1, sublist2 in zip(list_[:-1], list_[1:]):
        assert len(sublist1) == len(sublist2)
    for tuple_ in zip(*list_):
        set_ = set(tuple_)
        if len(set_) > 1:
            result.append('dc')
        else:
            result.append(tuple_[0])
    return result

def main():
    list1 = 'Sweet Bad No No Long Yes Bike No Yes'.split()
    list2 = 'Sweet Bad No No Long Yes Bike Yes No'.split()
    list3 = 'Sweet Bad No No Short Yes Car Yes No'.split()

    master_list = [ list1, list2, list3 ]
    pprint.pprint(master_list)
    result = rep_dc(master_list)
    print(result)
    result_string = ' '.join(result)
    print(result_string)

main()

Upvotes: 0

Guy Gavriely
Guy Gavriely

Reputation: 11396

>>> s = "Sweet Bad No No Long Yes Bike No Yes"
>>> s1 = "Sweet Bad No No Long Yes Bike Yes No"
>>> map(lambda x: x[0]==x[1] and x[0] or 'dc', zip(s.split(), s1.split()))
['Sweet', 'Bad', 'No', 'No', 'Long', 'Yes', 'Bike', 'dc', 'dc']
>>> ' '.join(_)
'Sweet Bad No No Long Yes Bike dc dc'

or:

>>> [x[0]==x[1] and x[0] or 'dc' for x in zip(s.split(), s1.split())]
['Sweet', 'Bad', 'No', 'No', 'Long', 'Yes', 'Bike', 'dc', 'dc']

Upvotes: 3

Related Questions