【问题标题】:Text data replacement using dictionary使用字典替换文本数据
【发布时间】:2019-04-11 21:37:47
【问题描述】:

具有以下结构的数据框 -

ID text
0  Language processing in python th is great
1  Relace the string 

字典命名自定义修复

{'Relace': 'Replace', 'th' : 'three'}

尝试了代码,输出如下 - 当前输出 -

ID text
0  Language processing in pythirdon three is great
1  Replace threee string 

代码:

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

  # For each match, look-up corresponding value in dictionary
  return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

df['col1'] = df.apply(lambda row: multiple_replace(custom_fix, row['text']), axis=1)

预期输出 -

ID text
0  Language processing in python three is great
1  Replace the string

【问题讨论】:

    标签: python dictionary nlp lookup


    【解决方案1】:

    我不是正则表达式专家,也许这不是最好的解决方案,但使用 正则表达式中的单词边界\b 应该可以解决问题,这里是固定功能:

    def multiple_replace(d, text):
        # Create a regular expression  from the dictionary keys
        regex = re.compile("(%s)" % "|".join(["\\b" + x + "\\b" for x in d.keys()]))
    
        # For each match, look-up corresponding value in dictionary
        return regex.sub(lambda mo: d[mo.string[mo.start():mo.end()]], text)
    
    

    【讨论】:

      【解决方案2】:

      你也可以拆分字符串来获取所有的单词并遍历列表。

          def multiple_replace(d, text):
              splitText=text.split()
              disc=len(set(splitText).intersection(set(d.keys())))
              if disc==0:    
                  return ' '.join(splitText)
              else:
                  for k in range(len(splitText)):      
                      try:        
                          splitText[k]=d[splitText[k]]        
                      except KeyError:        
                          pass
                  return ' '.join(splitText)
      

      希望对你有帮助。

      【讨论】:

      • 在效率方面,我相信有字典来替换会更快。你有什么想法?
      • 我也认为字典是一种更快的方法,但是生成列表是为了避免正则表达式的滚动效果。
      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2015-10-30
      • 1970-01-01
      • 2019-10-05
      • 2019-11-04
      相关资源
      最近更新 更多