【问题标题】:Splitting Sentences into Words when Formatting Tags are Present存在格式化标签时将句子拆分为单词
【发布时间】:2016-04-27 20:04:14
【问题描述】:

我使用以下正则表达式将句子拆分为单词:

"('?\w[\w']*(?:-\w+)*'?)"

例如:

import re
re.split("('?\w[\w']*(?:-\w+)*'?)","'cos I like ice-cream")

给予:

['', "'cos", ' ', 'I', ' ', 'like', ' ', 'ice-cream', '!']

但是,格式化标签有时会出现在我的文本中,而我的正则表达式显然无法按我的意愿处理它们:

re.split("('?\w[\w']*(?:-\w+)*'?)","'cos I <i>like</i> ice-cream!")

给予:

['', "'cos", ' ', 'I', ' <', 'i', '>', 'like', '</', 'i', '> ', 'ice-cream', '!']

虽然我愿意:

['', "'cos", ' ', 'I', ' <i>', 'like', '</i> ', 'ice-cream', '!']

你会如何解决这个问题?

【问题讨论】:

  • 只是好奇,为什么要保留''' ' 之类的空字符串?
  • @ccf 因为那时我知道奇数元素是单词,而偶数元素不是。

标签: regex


【解决方案1】:

您可以使用单词边界正则表达式,使用否定的lookbehind 和lookahead 断言指定排除匹配项:

^|(?<!['<\/-])\b(?![>-])

Regex demo.

很遗憾,python 正则表达式引擎不支持splitting on zero-width characters,因此您必须使用解决方法。

import re

a = re.sub(r"^|(?<!['<\/-])\b(?![>-])", "|", "'cos I <i>like</i> ice-cream!").split('|');
print(a)

#  ['', "'cos", ' ', 'I', ' <i>', 'like', '</i> ', 'ice-cream', '!']

Python demo.

【讨论】:

    【解决方案2】:
    # I added a negative lookahead to your pattern to assert bracket > is closed properly
    
    import re
    print re.split("('?\w[\w']*(?:-\w+)*'?(?!>))","'cos I <i>like</i> ice-cream!" )
    
    [Output]
    
    ['', "'cos", ' ', 'I', ' <i>', 'like', '</i> ', 'ice-cream', '!']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多