我正在尝试用其上的单词[NOUN]
替换字符串。我很无能为力!
下面是我的代码 - 它返回了很多错误 - 变量故事是一个字符串而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中的所有知识来解决这个问题了几个小时!
答案 0 :(得分: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]"
答案 1 :(得分:0)
错误“在分配前引用”是指:
length = len(story1)
story1 = story.split()
你应该先分配story1,然后再获取它的长度。
答案 2 :(得分: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]