【问题标题】:how to insert and replace a list of words in another list or a string in python如何插入和替换另一个列表中的单词列表或python中的字符串
【发布时间】:2013-03-14 03:42:38
【问题描述】:

我正在尝试用单词[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 中的所有知识来解决这个问题!

【问题讨论】:

    标签: python string list split replace


    【解决方案1】:

    “赋值前引用”的错误指的是这个:

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

    你应该先分配story1,然后得到它的长度。

    【讨论】:

    • 那之后的下一步是什么?
    • 现在它只返回“Lets play marbels”而不是“Let's play 'NOUN']
    【解决方案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]"
    

    【讨论】:

    • 不需要副本,它会在“I'm Benjamin”上失败,并带有“I'm [NOUN]jamin”。
    • @MarkTolonen 现在修复了这个问题。
    【解决方案3】:

    问题在于在设置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-17
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多