繁体   English   中英

如何插入和替换另一个列表中的单词列表或python中的字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM