[英]Regex in Python to detect ellipsis
我有一个大型文本语料库,我想对其进行一点处理,然后基于它训练 Word2Vec 模型。 在某些情况下,由于省略号而删除单词,例如:
但是看到他们给七八岁的孩子演奏是很美的
或者
这个国家处于独立前和独立后的内战的喧嚣中,但这里的气氛往往是欢乐的
现在我想撤消这些删除(分别是启发和第二个)。 这是我写的:
re.sub(r'- (and|to|or)( [^ -]+?){1,2}-(.+?)( |$|\n)', '-\\3 \\1\\2-\\3\\4', text)
但它不起作用,因为如果and/or/to
和第二个单词之间有多个单词-
,则只会显示第一个。 我想要的输出是:
但是看到他们给七岁和八岁的孩子演奏是很美的
和
这个国家处于独立前和独立后的内战的喧嚣中,但这里的气氛往往是欢乐的
我找到了解决方案:
re.sub(r'- (and|to|or)((?: [^ -]+?){1,2})-(.+?)( |$|\n)', '-\\3 \\1\\2-\\3\\4', text)
您可以使用
re.sub(r'\b-(\s+(?:and|to|or)(?:\s+\w+)*\s+\w+(-\w[\w-]*))', r'\2\1', text)
请参阅正则表达式演示。 详情:
\\b-
- 前面带有字符字符的连字符(\\s+(?:and|to|or)(?:\\s+\\w+)*\\s+\\w+(-\\w[\\w-]*))
- 第 1 组:
\\s+
- 一个或多个空格(?:and|to|or)
- and
, to
or or
(?:\\s+\\w+)*
- 零次或多次出现一个或多个空格,后跟一个或多个单词字符\\s+
- 一个或多个空格\\w+
- 一个或多个单词字符(-\\w[\\w-]*)
- 第 2 组:一个连字符、一个字符字符,然后是零个或多个单词或连字符字符。请参阅Python 演示:
import re
texts = ['But seeing them playing to seven- and eight-year-olds is beautiful', 'The country was in the uproar of pre- and then post-independence civil war but the mood here is most often joyous']
rx = r''
for text in texts:
print( re.sub(r'- (and|to|or)((?: [^ -]+?){1,2})-(.+?)( |$|\n)', '-\\3 \\1\\2-\\3\\4', text) )
输出:
But seeing them playing to seven-year-olds and eight-year-olds is beautiful
The country was in the uproar of pre-independence and then post-independence civil war but the mood here is most often joyous
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.