[英]how to insert and replace a list of words in another list or a string in python
我正在嘗試用它上面的單詞[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中的所有知識來解決這個問題幾個小時了!
這是解決問題的簡便方法。
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]"
“賦值前引用”錯誤指的是:
length = len(story1)
story1 = story.split()
你應該首先分配story1,然后獲取它的長度。
問題是在設置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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.