【问题标题】:I need a regular expression that will deal with apostrophes when extracting words from text [duplicate]从文本中提取单词时,我需要一个处理撇号的正则表达式[重复]
【发布时间】:2015-09-01 05:51:22
【问题描述】:

有人知道在使用正则表达式从文本中提取单词时处理撇号的方法吗?

>>> import re
>>> s = re.compile(r"\b[A-Za-z0-9_\-]+\b")
>>> s.findall("I don't know Sally's 'special' friend.")
['I', 'don', 't', 'know', 'Sally', 's', 'special', 'friend']

想要的结果:

['I', "don't", 'know', 'Sally', 'special', 'friend']

This discussion 涵盖了如何查找整个单词,但不处理撇号。

【问题讨论】:

标签: python regex text-parsing


【解决方案1】:
s = re.compile(r"(?:^|(?<=\s))[A-Za-z0-9_'\-]+(?=\s|$|\b)")

使用这个代替 \b.lookarounds 会为你工作。查看演示。

https://regex101.com/r/sS2dM8/25

【讨论】:

  • 谢谢。这会产生非常接近的结果:['I', "don't", 'know', "Sally's", "'special'"]
  • 虽然输了最后一个字('朋友')!
  • @Bill regex101.com/r/sS2dM8/26 现在它不会输了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2023-04-01
  • 2018-09-21
  • 1970-01-01
相关资源
最近更新 更多