【问题标题】:How to replace strings in sentence with appropriate dictionary values?如何用适当的字典值替换句子中的字符串?
【发布时间】:2021-02-01 04:05:02
【问题描述】:

我有一本字典如下:

dict_ = { 
        'the school in USA' : 'some_text_1',
        'school' : 'some_text_1',
        'the holy church in brisbane' : 'some_text_2',
        'holy church' : 'some_text_2'
}

还有一个句子列表如下:

text_sent = ["Ram is going to the holy church in brisbane",\
             "John is going to holy church", \
             "shena is going to the school in USA", \
             "Jennifer is going to the school"]

我想用 text_sent 中的相应值替换出现的 dict_ 字典键。我这样做如下:

for ind, text in enumerate(text_sent) :
    for iterator in dict_.keys() :
        if iterator in text : 
            text_sent[ind] = re.sub(iterator, dict_[iterator], text)

for i in text_sent:
    print(i)

我得到的输出如下:

Ram is going to the some_text_2 in brisbane
John is going to some_text_2
shena is going to the some_text_1 in USA
Jennifer is going to the some_text_1

预期输出是:

Ram is going to some_text_2
John is going to some_text_2
shena is going to some_text_1
Jennifer is going to some_text_1

我需要的是,较长的字符串(例如,“布里斯班的圣堂”)需要替换,以防万一,句子中没有完整的字符串, 只有这样才能使用较小的版本(例如,'holy church')而不是较长的版本来替换 text_sent 句子中的相应值。

【问题讨论】:

    标签: python string list dictionary


    【解决方案1】:

    您可以使用re.sub 进行替换,使用str.join 格式化子字符串字典中的正则表达式:

    import re
    d = {'the school in USA': 'some_text_1', 'school': 'some_text_1', 'the holy church in brisbane': 'some_text_2', 'holy church': 'some_text_2'}
    text_sent = ["Ram is going to the holy church in brisbane",\
             "John is going to holy church", \
             "shena is going to the School in USA", \
             "Jennifer is going to the school"]
    
    r = [re.sub('|'.join(d), lambda x:d[x.group()], i, re.I) for i in text_sent]
    

    输出:

    ['Ram is going to some_text_2', 'John is going to some_text_2', 'shena is going to some_text_1', 'Jennifer is going to the some_text_1']
    

    【讨论】:

    • 我是初级程序员。您能否解释一下 d[x.group()] 究竟是如何工作的?
    • @rishikeshfulari 当正则表达式找到匹配项时,re.sub 函数通过lambda 函数的参数提供对匹配值的访问。找到匹配项时调用lambda x:d[x.group()]d[x.group()]d 中查找匹配项并返回其值。
    • 如果我在“shena is going to the school in USA”中将“school”的大小写改为“School”,则无法替换。您能否建议更改此代码以使比较不区分大小写?我无法将完整句子的大小写转换为 lower(),因为我们需要保留其他单词的大小写。但是,如果字典中存在不同大小写的对应键,程序应该能够改变句子中单词的大小写。
    • @rishikeshfulari 请看我最近的编辑。 re.I 标志可用于忽略匹配文本的大小写。
    【解决方案2】:

    您可以为字典创建一个辅助列表,并根据其元素长度对其进行排序。

    dict_ = {'the school in USA' : 'some_text_1',
             'school' : 'some_text_1',
             'the holy church in brisbane' : 'some_text_2',
             'holy church' : 'some_text_2'}
    
    text_sent = ["Ram is going to the holy church in brisbane",
                 "John is going to holy church",
                 "shena is going to the school in USA",
                 "Jennifer is going to the school"]
    
    dict_keys = list(dict_.keys())
    dict_keys.sort(key=len)
    dict_keys.reverse()
    
    text_sent_replaced = []
    for text in text_sent:
        modified_text = text
        for key in dict_:
            modified_text = modified_text.replace(key,dict_[key])
        text_sent_replaced.append(modified_text)
    
    print(text_sent_replaced)
    

    【讨论】:

      【解决方案3】:

      主要问题是您没有添加break 语句。如果稍后在 dict_ 字典中有多个匹配项,则您将覆盖值。试试这个:

      for ind, text in enumerate(text_sent) :
          for iterator in dict_.keys() :
              if iterator in text :
                  text_sent[ind] = re.sub(iterator, dict_[iterator], text)
                  break
      

      【讨论】:

        【解决方案4】:

        只要替换的元素位于每行的末尾,这将在不使用 re 的情况下完成任务,就像您的示例中的情况一样:

        for ind, text in enumerate(text_sent) :
            for iterator in dict_.keys() :
                if iterator in text :
                    text_sent[ind] = text.split(iterator)[0] + dict_[iterator]
        
        for i in text_sent:
            print(i)
        
        #Prints:
        #Ram is going to the some_text_2
        #John is going to some_text_2
        #shena is going to the some_text_1
        #Jennifer is going to the some_text_1
        

        【讨论】:

          猜你喜欢
          • 2022-01-13
          • 2018-09-11
          • 2017-07-15
          • 2014-06-09
          • 2022-01-15
          • 1970-01-01
          • 2019-05-29
          • 1970-01-01
          • 2020-09-22
          相关资源
          最近更新 更多