繁体   English   中英

在Python中使用正则表达式

[英]Using regular expressions in Python

我正在努力从字符串中剪掉第一句话的问题。 如果我没有以点号结尾的缩写,那将不是一个问题。

所以我的例子是:

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

结果应该是:

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

通常我会这样做:

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

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

我带着几个表情来了,但是他们都没有。

您可以尝试NLTK的Punkt句子令牌生成器 ,它使用一种真正的算法来执行此类操作,以找出缩写是什么,而不是您的缩写的临时集合。

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.

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

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.'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM