2013-03-24 102 views
0

我試圖用它替換字[NOUN]的字符串。我無能爲力!如何插入和替換另一個列表中的單詞列表或python中的字符串

這裏是我下面的代碼 - 它會返回大量的錯誤 - 變量故事是一個字符串,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

錯誤「賦值之前引用」指的是這樣的:

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

你應該首先分配story1,然後獲取它的長度。

+0

,什麼是之後的下一步是什麼? – 2013-03-24 17:31:44

+0

現在它只是返回「讓我們玩大理石」而不是「讓我們玩''NOUN'] – 2013-03-24 17:33:21

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]" 
+0

沒有必要複製,它會在」我是本傑明「和」我是[NOUN] jamin「時失敗。 – 2013-03-24 17:54:38

+0

@MarkTolonen現在修復了這個問題。 – 2013-03-24 18:05:59

0

的問題是從設置story1的值之前計算story1的長度。

這是一個固定版本,它也以更「pythonic」的方式進行迭代,修復了加入原始字符串而不是拆分字符串的bug。

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] 
相關問題