【问题标题】:How to keep specific words when preprocessing words for NLP?(str.replace & regex)为 NLP 预处理单词时如何保留特定单词?(str.replace & regex)
【发布时间】:2019-10-08 02:44:08
【问题描述】:

我想删除除“3d”这个词之外的数字。 我尝试了一些方法但失败了。 请看下面我的简单代码:


s = 'd3 4 3d'
rep_ls = re.findall('([0-9]+[a-zA-Z]*)', s)

>> ['3', '4', '3d']

for n in rep_ls:
    if n == '3d':
        continue
    s = s.replace(n, '')

>> s = 'd  d'
>> expected = 'd 3d'

【问题讨论】:

  • 如果字符串类似于 123d123123d1231123d 怎么办?期望的输出应该是什么?
  • @CodeManiac 我仍然希望返回 3d

标签: python regex nlp


【解决方案1】:

要删除除单词 3d 之外的所有数字,您可以使用否定前瞻 (?! 来断言直接在右侧的不是单词边界之间的 3d \b

然后匹配1+位数\d+

在替换中使用空字符串。

(?!\b3d\b)\d+

Regex demo

【讨论】:

    【解决方案2】:

    你已经很接近了,你只需要将值按空格分割,然后循环遍历该值,如果该值为3d,则不要更改,否则更改它

    import re;
    s = 'd3 4 3d'
    rep_ls = re.split(r'\s+', s)
    
    final = ''
    for n in rep_ls:
        if n == '3d':
            final +=' 3d'
            continue
        final +=  ' ' + re.sub(r'\d+','',n)
    
    
    print(final)
    

    当索引为0时,修剪字符串末尾的多余空格或使用if语句不添加空格


    或者您可以使用字典并稍后加入它们

    import re;
    s = 'd3 4 3d'
    rep_ls = re.split(r'\s+', s)
    
    final = []
    for n in rep_ls:
        if n == '3d':
            final.append(n)
            continue
        final.append(re.sub(r'\d+','',n))
    
    final = " ".join(final)    
    print(final)
    

    输出是>>d 3d

    【讨论】:

      【解决方案3】:

      也许,这个表情,

      (?i)(3d)\b|(\D+)|\d+
      

      可能适用于re.sub\1\2

      Demo

      如果3D 也是不受欢迎的,我们在这里假设不是这样,那么可以安全地删除(?i)

      (3d)\b|(\D+)|\d+
      

      3d 之外,您希望保留的任何其他内容都将进入第一个捕获组:

      (3d|4d|anything_else)\b|(\D+)|\d+
      

      测试

      import re
      
      regex = r'(?i)(3d)\b|(\D+)|\d+'
      string = '''d3 4 3d'''
      
      print(re.sub(regex, r'\1\2', string))
      

      输出

      d 3d
      

      Demo 2

      正则表达式电路

      jex.im 可视化正则表达式:

      【讨论】:

      • 打印出d d - Demo
      • >> expected = 'd 3d'
      猜你喜欢
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2020-05-25
      • 2020-10-20
      • 1970-01-01
      • 2018-08-24
      • 2018-08-21
      • 2023-03-30
      相关资源
      最近更新 更多