【问题标题】:Regex in Python to detect ellipsisPython中的正则表达式检测省略号
【发布时间】:2021-10-27 10:24:01
【问题描述】:

我有一个大型文本语料库,我想对其进行一些处理,然后基于它训练一个 Word2Vec 模型。也有因省略号而删除单词的情况,如:

但是看到他们为 7-8 岁的孩子演奏 很美

该国处于pre-独立后内战的喧嚣中,但这里的情绪通常是欢乐的

现在我想撤消这些删除(分别是inspiredsecond)。这是我写的:

re.sub(r'- (and|to|or)( [^ -]+?){1,2}-(.+?)( |$|\n)', '-\\3 \\1\\2-\\3\\4', text)

但它不起作用,因为如果and/or/to 和带有- 的第二个单词之间有多个单词,则只会显示第一个单词。 我想要的输出是:

但是看到他们和 7 岁的孩子8 岁的孩子 一起玩很漂亮

该国处于独立前独立后内战的喧嚣中,但这里的情绪通常是欢乐的

【问题讨论】:

  • 请为您的示例添加明确的所需输出。

标签: python regex nlp text-processing


【解决方案1】:

我找到了解决办法:

re.sub(r'- (and|to|or)((?: [^ -]+?){1,2})-(.+?)( |$|\n)', '-\\3 \\1\\2-\\3\\4', text)

【讨论】:

    【解决方案2】:

    你可以使用

    re.sub(r'\b-(\s+(?:and|to|or)(?:\s+\w+)*\s+\w+(-\w[\w-]*))', r'\2\1', text)
    

    请参阅regex demo详情

    • \b- - 以字符开头的连字符
    • (\s+(?:and|to|or)(?:\s+\w+)*\s+\w+(-\w[\w-]*)) - 第 1 组:
      • \s+ - 一个或多个空格
      • (?:and|to|or) - andtoor
      • (?:\s+\w+)* - 零次或多次出现一个或多个空格,后跟一个或多个单词字符
      • \s+ - 一个或多个空格
      • \w+ - 一个或多个单词字符
      • (-\w[\w-]*) - 第 2 组:一个连字符、一个单词字符,然后是零个或多个单词或连字符字符。

    Python demo

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多