0

我正在尝试用[NOUN]上面的单词替换一个字符串。我一无所知!

下面是我的代码-它返回很多错误-变量story是一个字符串,listOfNouns是一个列表-所以我尝试通过拆分将字符串转换为列表。:

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

这是我在调用上述函数时收到的错误消息
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

如何用另一个列表中的另一个元素替换新的 story1 列表?

如何修改元组并返回新字符串 - 应该说:
Let's play [NOUN]???

有人可以帮忙吗?我迷路了,我已经尝试了几个小时,使用我在 Python/Java 中的所有知识来解决这个问题!

4

3 回答 3

2

这是解决问题的更短更简单的方法。

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

输出

In [4]: replacement('Let\'s play marbles, I\'m Ben', ['marbles', 'Ben'])
Out[4]: "Let's play [NOUN], I'm [NOUN]"
于 2013-03-24T17:46:43.640 回答
0

错误“分配前引用”指的是:

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

您应该首先分配story1,然后获取它的长度。

于 2013-03-24T17:27:06.750 回答
0

问题在于在设置story1的值之前计算story1的长度。

这是一个固定版本,它也以更“pythonic”的方式进行迭代,并修复了加入原始字符串而不是拆分字符串的错误。

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']))

输出:

Let's play [NOUN]

这是另一种解决方案,它使用正则表达式一次有效地替换单词的所有实例,而不替换包含该单词的部分单词。

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()))

输出:

The quick brown [NOUN] jumped over the foxy [NOUN].
[NOUN] foxy [NOUN] [NOUN] ladies [NOUN] foxy [NOUN]
于 2013-03-24T17:49:57.260 回答