2016-09-02 24 views
0

我已經看到了這個問題以前的反應,但他們都不是最近和他們都不在Python 3工作對我來說我有一個字符串列表,我只是想確定哪些包含的表情符號。什麼是最快的方法來做到這一點?如何確定一個Python字符串是否包含表情符號?

更具體地說,我有一個來自AB測試的電子郵件主題行的冗長列表,我試圖確定哪些主題行包含表情符號。

+3

表情符號或表情符號?無論如何,你必須首先確定這對你意味着什麼。 –

+0

我會建議嘗試[this](http://stackoverflow.com/a/28327594/6464893)。 – Harrison

+0

大多數以前的解決方案應該很好地轉化爲Python 3.請發佈一個讓您覺得「應該工作」的錯誤消息,因此我們可以幫助解決您的具體問題。 – Prune

回答

1

this linkthis link兩者都計數©和其他常見字符作爲表情符號。前者也有輕微的錯誤,後者依然不起作用。

下面是使用this newer datathis documentation在保守方面犯錯的實現。它只考慮用unicode屬性Emoji_Presentation(這意味着它絕對是表情符號)標記的代碼點,或者僅用屬性Emoji標記的代碼點(這意味着它默認爲文本,但它可能是可能是是表情符號),那是然後是一個特殊的變化選擇器代碼點fe0f,它表示默認爲表情符號。我說這是保守的原因是因爲某些系統並不如挑剔fe0f,並會將字符的表情符號,無論他們可以(閱讀更多關於這個here)。

import re 
from collections import defaultdict 


def parse_line(line): 
    """Return a pair (property, codepoints) where property is a string and 
     codepoints is a set of int unicode code points""" 
    pat = r'([0-9A-Z]+)(\.\.[0-9A-Z]+)? + ; +(\w+) + #.*' 
    match = re.match(pat, line) 
    assert match 

    codepoints = set() 

    start = int(match.group(1), 16) 

    if match.group(2): 
     trimmed = match.group(2)[2:] 
     end = int(trimmed, 16) + 1 
    else: 
     end = start + 1 

    for cp in range(start, end): 
     codepoints.add(cp) 

    return (match.group(3), codepoints) 


def parse_emoji_data(): 
    """Return a dictionary mapping properties to code points""" 
    result = defaultdict(set) 
    with open('emoji-data.txt', mode='r', encoding='utf-8') as f: 
     for line in f: 
      if '#' != line[0] and len(line.strip()) > 0: 
       property, cp = parse_line(line) 
       result[property] |= cp 
    return result 


def test_parse_emoji_data(): 
    sets = parse_emoji_data() 
    sizes = { 
     'Emoji': 1123, 
     'Emoji_Presentation': 910, 
     'Emoji_Modifier': 5, 
     'Emoji_Modifier_Base': 83, 
    } 
    for k, v in sizes.items(): 
     assert len(sets[k]) == v 


def contains_emoji(text): 
    """ 
    Return true if the string contains either a code point with the 
    `Emoji_Presentation` property, or a code point with the `Emoji` 
    property that is followed by \uFE0F 
    """ 
    sets = parse_emoji_data() 
    for i, ch in enumerate(text): 
     if ord(ch) in sets['Emoji_Presentation']: 
      return True 
     elif ord(ch) in sets['Emoji']: 
      if len(text) > i+1 and text[i+1] == '\ufe0f': 
       return True 
    return False 

test_parse_emoji_data() 
assert not contains_emoji('hello') 
assert not contains_emoji('hello :) :D 125% #%&*(@#%&[email protected](^*(') 
assert contains_emoji('here is a smiley \U0001F601 !!!') 

要運行此操作,您需要在工作目錄中使用ftp://ftp.unicode.org/Public/emoji/3.0/emoji-data.txt

一旦正則表達式模塊支持表情符號屬性,它將更容易使用它。

相關問題