0

I am trying to replace a string with the word [NOUN] on it. I'm clueless!

Here's my code below - which returns lots of errors - the variable story is a string and listOfNouns is a list - so I try and convert the string into a list by splitting it.:

def replacement(story, listOfNouns):   
    length = len(story1)
    story1 = story.split()
    for c in range(0,len(story1)):
        if c in listOfNouns:
             story1[c]= 'NOUN'
             story = ''.join(story)      
    return story

Here's the error message that I get below when I call the above function with
replacement("Let's play marbles", ['marbles']):

Traceback (most recent call last):
  File "<pyshell#189>", line 1, in <module>
    replacement("Let's play marbels", ['marbels'])
  File "C:/ProblemSet4/exam.py", line 3, in replacement
    length = len(story1)
UnboundLocalError: local variable 'story1' referenced before assignment

How can I replace the new story1 list with another element from another list?

How do I modify the tuples and return the new string - which is supposed to say:
Let's play [NOUN]???

Can anyone please help out? I'm lost and i've been trying this for hours using all the knowledge I have in Python/Java to figure this crap out!

3 Answers 3

2

Here's a shorter and simpler way of solving your problem.

def replacement(story, nouns):
    return ' '.join('[NOUN]' if i in nouns else i for i in story.split())

Output

In [4]: replacement('Let\'s play marbles, I\'m Ben', ['marbles', 'Ben'])
Out[4]: "Let's play [NOUN], I'm [NOUN]"
Sign up to request clarification or add additional context in comments.

2 Comments

There is no need for the copy, and it would fail on "I'm Benjamin" with "I'm [NOUN]jamin".
@MarkTolonen fixed that now.
0

The error "referenced before assignment" refers to this:

length = len(story1)
story1 = story.split()

You should first assign story1, then get its length.

2 Comments

and what is the next step after that?
now it just returns "Lets play marbels" instead of "Let's play 'NOUN']
0

The problem is from calculating the length of story1 before setting the value of story1.

Here's a fixed version that also iterates in a more "pythonic" way and fixes the bug of joining the original string and not the split string.

def replacement(story, listOfNouns):   
    story1 = story.split()
    for i,word in enumerate(story1):
        if word in listOfNouns:
             story1[i] = '[NOUN]'
    return ' '.join(story1)      

print(replacement("Let's play marbles", ['marbles']))

Output:

Let's play [NOUN]

Here's another solution that efficiently replaces all instances of the words at once using a regular expression, without replacing parts of words containing the word.

import re

stories = [
    'The quick brown fox jumped over the foxy lady.',
    'Fox foxy fox lady ladies lady foxy fox']

def replacement(story, listOfNouns):
    story = re.sub(r'''
        (?ix)   # ignore case, allow verbose regular expression definition
        \b      # word break
        (?:{})  # non-capturing group, string to be inserted
        \b      # word break
        '''.format('|'.join(listOfNouns)),'[NOUN]',story) # OR all words.
    return story

for story in stories:
    print(replacement(story,'fox lady'.split()))

Output:

The quick brown [NOUN] jumped over the foxy [NOUN].
[NOUN] foxy [NOUN] [NOUN] ladies [NOUN] foxy [NOUN]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.