在Python中使用正则表达式

时间:2012-04-03 15:40:33

标签: python expression

我正在努力解决问题,从字符串中删除第一句话。 如果我没有以点结尾的缩写,那就不会出现这样的问题。

所以我的例子是:

  • string ='我喜欢奶酪,汽车等,但我最喜欢的网站是stackoverflow。我的新马叫做兰迪。'

结果应该是:

  • 结果='我喜欢奶酪,汽车等,但我最喜欢的网站是stackoverflow。'

通常我会这样做:

re.findall(r'^(\s*.*?\s*)(?:\.|$)', event)

但是我想跳过一些预定义的词,比如上面提到的等。

我带来了几个表情,但没有一个有效。

2 个答案:

答案 0 :(得分:4)

您可以尝试NLTK's Punkt sentence tokenizer,它使用真实的算法来确定缩写的内容,而不是您的特殊缩写集合。

NLTK包括一个预先训练好的英语;加载它:

nltk.data.load('tokenizers/punkt/english.pickle')

来自源代码:

>>> sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
>>> print '\n-----\n'.join(sent_detector.tokenize(text.strip()))
Punkt knows that the periods in Mr. Smith and Johann S. Bach
do not mark sentence boundaries.
-----
And sometimes sentences 
can start with non-capitalized words.
-----
i is a good variable
name.

答案 1 :(得分:1)

在句子结尾字符后查找第一个大写字母怎么样?当然,这不是万无一失的。

import re
r = re.compile("^(.+?[.?!])\s*[A-Z]")
print r.match('I like cheese, cars, etc. but my the most favorite website is stackoverflow. My new horse is called Randy.').group(1)

输出

'I like cheese, cars, etc. but my the most favorite website is stackoverflow.'
相关问题