如何从文本中删除除文字和表情符号之外的所有内容?

时间:2017-05-21 20:03:26

标签: python regex string replace emoji

作为文本分类问题的一部分,我正在尝试清理文本数据集。到目前为止,我正在删除除文本之外的所标点符号,数字,表情符号 - 一切都被删除了。现在我正在尝试使用表情符号作为功能因此我想保留单词以及表情符号。

首先,我在文本中搜索表情符号,并将它们与其他单词/表情符号分开。这是因为每个表情符号应该单独/分开处理。所以我搜索一个表情符号并在其两端填充空格。

但是在弄清楚如何将已知的正则表达式与单词和表情符号结合起来时,我感到很茫然。这是我目前的代码:

import re

def clean_text(raw_text):

    padded_emoji_text = pad_emojis(raw_text)
    print("Emoji padded text: " + padded_emoji_text)

    reg = re.compile("[^a-zA-Z]") # line a

    # old regex to remove everything except words  
    letters_only_text = reg.sub(' ', raw_text)
    print("Cleaned text: " + letters_only_text)

    # Code to remove everything except text and emojis
    # How?

def pad_emojis(raw_text):

    print("Original Text: " + raw_text)

    reg = re.compile(u'['
      u'\U0001F300-\U0001F64F'
      u'\U0001F680-\U0001F6FF'
      u'\u2600-\u26FF\u2700-\u27BF]', 
      re.UNICODE)

    #padding the emoji with space at both ends
    new_text = reg.sub(r' \g<0> ',raw_text) 

    return new_text

text = "I am very #happy man! but my wife is not . 99/33"
clean_text(text)

目前的o / p:

Original Text: I am very #happy man! but my wife is not . 99/33
Emoji padded text: I am very #happy man! but     my wife   is not     . 99/33
Cleaned text: I am very  happy man  but   my wife  is not

我想要实现的目标:

I am very happy man but     my wife   is not    

问题:

1)如何将表情符号正则表达式与正则表达式一起添加到正则表达式编译中? (第一行)

2)我也能以更好的方式实现我所寻求的目标,即无需编写单独的函数来分离表情符号并用空格填充它们吗?我不知何故觉得这可以避免。

1 个答案:

答案 0 :(得分:1)

You may join the two steps into one using a single regex and a lambda expression inside a re.sub like this:

import re

emoji_pat = '[\U0001F300-\U0001F64F\U0001F680-\U0001F6FF\u2600-\u26FF\u2700-\u27BF]'
shrink_whitespace_reg = re.compile(r'\s{2,}')

def clean_text(raw_text):
    reg = re.compile(r'({})|[^a-zA-Z]'.format(emoji_pat)) # line a
    result = reg.sub(lambda x: ' {} '.format(x.group(1)) if x.group(1) else ' ', raw_text)
    return shrink_whitespace_reg.sub(' ', result)

text = 'I am very #happy man! but my wife is not . 99/33'
print('Cleaned text: ' + clean_text(text))
# => Cleaned text: I am very happy man but   my wife  is not  

See the Python demo

<强>解释

  • 第一个正则表达式看起来像([\U0001F300-\U0001F64F\U0001F680-\U0001F6FF\u2600-\u26FF\u2700-\u27BF])|[^A-Za-z]并且将匹配并捕获到组1中的表情符号,或者只匹配除ASCII字母之外的任何字符。如果捕获了表情符号(请参阅lambda内的if x.group(1)),表情符号将返回封闭,两侧都有空格,否则,该空格将用于替换非字母
  • \s{2,}模式将匹配2个或更多空格,shrink_whitespace_reg.sub(' ', result)将使用单个空格替换所有这些块。