سؤال

I have a set of tuples of the form

ref_set = [(a1,b1),(a2,b2),(a3,b3)...]   

and so on. I need to compare words from a list of sentences and check if it is equal to a1, a2, a3.. if word == a1, replace it with b1. If word == a2, replace with b2 and so on.

Here's my code:

def replace_words(x): #function
    for line in x: #iterate over lines in list
        for word in line.split(): #iterate over words in list
            for i,j in ref_set: #iterate over each tuple
                if word == i: #if word is equal to first element
                   word = j  #replace it with 2nd one.  

I'm getting None as a result; I know I need to return something.

هل كانت مفيدة؟

المحلول

Don't use a list of tuples. Use a dictionary:

ref_map = dict(ref_set)

for line in x:
    line = ' '.join([ref_map.get(word, word) for word in line.split()])

otherwise you have a NxM loop; for every extra word in your text or in your ref_set you double the number of iterations you need to do.

Your code only rebinds word, not replace the word in the line; the list comprehension above produces a new line value instead. This doesn't replace the line in x though, you need another list comprehension for that:

x = [' '.join([ref_map.get(word, word) for word in line.split()]) for line in x]

It appears from the comments that x is not a list of sentences but rather one sentence. In which case you use just process that one line with one list comprehension, as in the loop iteration over x above:

def corrected(line):
    return ' '.join([ref_map.get(word, word) for word in line.split()])
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top