Python emoji.demojize() Examples

The following are 14 code examples of emoji.demojize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module emoji , or try the search function .
Example #1
Source File: data_loader.py    From SemEval2019Task3 with MIT License 5 votes vote down vote up
def processing_pipelie(text):
    text = text.lower().strip()
    text = emoji.demojize(text, delimiters=(' ', ' '))
    text = ' '.join(text_processor.pre_process_doc(text))
    text = remove_underscope_for_emoji(text)
    return text 
Example #2
Source File: tweet_processor.py    From SemEval2019Task3 with MIT License 5 votes vote down vote up
def tweet_process(text):
    text = ' '.join(text_processor.pre_process_doc(remove_tags(text)))
    text = emoji.demojize(text, delimiters=(' ', ' '))
    tokens = text.split()
    ret_list = []
    for token in tokens:
        if len(token) > 3 and '_' in token:
            token = token.replace('_', ' ')

        if token[0] == '<' and token[-1] == '>':
            token = token[1:-1]

        ret_list.append(token)
    text = ' '.join(ret_list)
    return text 
Example #3
Source File: tweet_processor.py    From SemEval2019Task3 with MIT License 5 votes vote down vote up
def processing_pipeline(text):
    text = text.lower().strip()
    # text = remove_dup_emoji(text)
    text = ' '.join(text_processor.pre_process_doc(text))
    text = emoji.demojize(text, delimiters=(' ', ' '))
    text = remove_underscope_for_emoji(text)
    return text



# print(processing_pipelie('e day હત ા શ ા ર ો ગ મ ા ટ ે હ ો મ ી ય ો પ ે થ ી homeop')) 
Example #4
Source File: plotter.py    From message-analyser with MIT License 5 votes vote down vote up
def barplot_emojis(msgs, your_name, target_name, topn, path_to_save):
    sns.set(style="whitegrid")

    mc_emojis = stools.get_emoji_countered(msgs).most_common(topn)
    if not mc_emojis:
        return
    your_msgs = [msg for msg in msgs if msg.author == your_name]
    target_msgs = [msg for msg in msgs if msg.author == target_name]

    your_emojis_cnt = stools.get_emoji_countered(your_msgs)
    target_emojis_cnt = stools.get_emoji_countered(target_msgs)

    df_dict = {"name": [], "emoji": [], "num": []}
    for e, _ in mc_emojis:
        df_dict["emoji"].extend([emoji.demojize(e), emoji.demojize(e)])
        df_dict["name"].append(your_name)
        df_dict["num"].append(your_emojis_cnt[e])
        df_dict["name"].append(target_name)
        df_dict["num"].append(target_emojis_cnt[e])

    ax = sns.barplot(x="num", y="emoji", hue="name", data=pd.DataFrame(df_dict), palette="PuBu")
    ax.set(ylabel="emoji name", xlabel="emojis")
    ax.legend(ncol=1, loc="lower right", frameon=True)

    fig = plt.gcf()
    fig.set_size_inches(11, 8)
    plt.tight_layout()

    fig.savefig(os.path.join(path_to_save, barplot_emojis.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_emojis.__name__} was created.")
    plt.close("all") 
Example #5
Source File: player.py    From PyRoyale with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, client, name, team, match, skin):
        self.client = client
        self.server = client.server
        self.match = match
        self.skin = skin
        
        self.name = ' '.join(emoji.emojize(re.sub(r"[^\x00-\x7F]+", "", emoji.demojize(name)).strip())[:20].split()).upper()
        self.team = team
        if len(self.team) > 0 and self.server.checkCurse(self.name):
            self.name = str()
        if len(self.name) == 0:
            self.name = self.server.defaultName
        self.pendingWorld = None
        self.level = int()
        self.zone = int()
        self.posX = int()
        self.posY = int()
        self.dead = True
        self.win = bool()
        self.voted = bool()
        self.loaded = bool()
        self.lobbier = bool()
        self.lastUpdatePkt = None

        self.trustCount = int()
        self.lastX = int()
        self.lastXOk = True
        
        self.id = match.addPlayer(self) 
Example #6
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def is_unicode(text):
    demojized = demojize(text)
    if demojized.count(':') != 2:
        return False
    if demojized.split(':')[2] != '':
        return False
    return demojized != text 
Example #7
Source File: translate.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        text = previous_message.message
        lan = input_str or "ml"
    elif "|" in input_str:
        lan, text = input_str.split("|")
    else:
        await event.edit("`.tr LanguageCode` as reply to a message")
        return
    text = emoji.demojize(text.strip())
    lan = lan.strip()
    translator = Translator()
    try:
        translated = translator.translate(text, dest=lan)
        after_tr_text = translated.text
        # TODO: emojify the :
        # either here, or before translation
        output_str = """**TRANSLATED** from {} to {}
{}""".format(
            translated.src,
            lan,
            after_tr_text
        )
        await event.edit(output_str)
    except Exception as exc:
        await event.edit(str(exc)) 
Example #8
Source File: util.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def deform_emojis(text):
    """ Convert unicode emojis into their text form """
    new_text = ""
    emojiless_text = ""
    data = regex.findall(r"\X", text)
    emojis_in_text = []

    for word in data:
        if any(char in UNICODE_EMOJI for char in word):
            word_emoji = emoji.demojize(word).replace(":", "").replace("_", " ")
            if word_emoji not in emojis_in_text:  # do not add an emoji if
                # already exists in text
                emojiless_text += " "
                new_text += " ({}) ".format(word_emoji)
                emojis_in_text.append(word_emoji)
            else:
                emojiless_text += " "
                new_text += " "  # add a space [instead of an emoji to be
                # duplicated]

        else:
            new_text += word
            emojiless_text += word

    emojiless_text = remove_extra_spaces(emojiless_text)
    new_text = remove_extra_spaces(new_text)

    return new_text, emojiless_text 
Example #9
Source File: translate.py    From X-tra-Telegram with Apache License 2.0 5 votes vote down vote up
def _(event):
    if event.fwd_from:
        return
    if "trim" in event.raw_text:
        # https://t.me/c/1220993104/192075
        return
    input_str = event.pattern_match.group(1)
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        text = previous_message.message
        lan = input_str or "ml"
    elif "|" in input_str:
        lan, text = input_str.split("|")
    else:
        await event.edit("`.tr LanguageCode` as reply to a message")
        return
    text = emoji.demojize(text.strip())
    lan = lan.strip()
    translator = Translator()
    try:
        translated = translator.translate(text, dest=lan)
        after_tr_text = translated.text
        # TODO: emojify the :
        # either here, or before translation
        output_str = """**TRANSLATED** from {} to {}
{}""".format(
            translated.src,
            lan,
            after_tr_text
        )
        await event.edit(output_str)
    except Exception as exc:
        await event.edit(str(exc)) 
Example #10
Source File: voting.py    From Chaos with MIT License 5 votes vote down vote up
def parse_comment_for_vote(body):
    """ turns a comment into a vote, if possible """
    return parse_emojis_for_vote(demojize(body)) 
Example #11
Source File: facebook_messenger_conversation.py    From FacebookChatStatistics with MIT License 5 votes vote down vote up
def top_emojis(self, nbr):
        """Returns the top `nbr` emojis used and who sent them.

        Args:
            nbr (int): The number of emojis to include in top list.

        Returns:
            tuple: List of top emojis and dict showing how many of
                these were sent by each participant.

        """
        emojis = {e: 0 for e in iter(emoji.UNICODE_EMOJI.values())}
        emojis_p = {p: 0 for p in self.p}
        for p in emojis_p:
            emojis_p[p] = {e: 0 for e in iter(emoji.UNICODE_EMOJI.values())}
        for message in self.data['messages']:
            if 'content' in message and len(message) == 4:
                msg = message['content']
                sender = message['sender_name']
                for c in msg:
                    emoji_str = emoji.demojize(c)
                    if emoji_str in emojis:
                        emojis_p[sender][emoji_str] += 1
                        emojis[emoji_str] += 1
        top_emojis = [emoji_key for emoji_key, count in sorted(emojis.items(),
                                       key=lambda kv: (-kv[1], kv[0]))[:nbr]]
        emojis_count_p = {p: {} for p in self.p}
        for p in self.p:
                emojis_count_p[p] = [emojis_p[p][e] for e in top_emojis]
        top_emojis = [emoji.emojize(top_emoji) for top_emoji in top_emojis]
        return top_emojis, emojis_count_p 
Example #12
Source File: sun.py    From sub with MIT License 5 votes vote down vote up
def build_say_payload(self, room, bot, text, apikey):
        """ Lingr """
        demoji = emoji.demojize(text)

        return {
            'room': room,
            'bot': bot,
            'text': demoji,
            'bot_verifier': hashlib.sha1(bot + apikey).hexdigest(),
        } 
Example #13
Source File: sun.py    From sub with MIT License 5 votes vote down vote up
def say(self, slack=False, lingr=True):
        resp = "\n".join(tuple(self.response())).rstrip("\n")
        if slack:
            j = {}
            j["text"] = resp
            print(json.dumps(j))
            # Lingr にも話す
            self.sub.say_lingr(message=resp, anti_double=False)
            lingr = False

        if lingr:
            resp_demoji = emoji.demojize(resp)
            print(resp_demoji, end='')
            if not self.passerby_channel:
                self.sub.say_slack(message=resp, anti_double=False) 
Example #14
Source File: comment_util.py    From FacebookPy with GNU General Public License v3.0 4 votes vote down vote up
def comment_image(browser, username, comments, blacklist, logger, logfolder, Settings):
    """Checks if it should comment on the image"""
    # check action availability
    if quota_supervisor(Settings, "comments") == "jump":
        return False, "jumped"

    rand_comment = random.choice(comments).format(username)
    rand_comment = emoji.demojize(rand_comment)
    rand_comment = emoji.emojize(rand_comment, use_aliases=True)

    open_comment_section(browser, logger)
    comment_input = get_comment_input(browser)

    try:
        if len(comment_input) > 0:
            comment_input[0].clear()
            comment_input = get_comment_input(browser)
            # below, an extra space is added to force
            # the input box to update the reactJS core
            comment_to_be_sent = rand_comment + " "

            browser.execute_script(
                "arguments[0].value = arguments[1];",
                comment_input[0],
                comment_to_be_sent,
            )
            # below, it also will remove that extra space added above
            # COS '\b' is a backspace char in ASCII
            comment_input[0].send_keys("\b")
            comment_input = get_comment_input(browser)
            comment_input[0].submit()
            update_activity(Settings, "comments")

            if blacklist["enabled"] is True:
                action = "commented"
                add_user_to_blacklist(
                    username, blacklist["campaign"], action, logger, logfolder
                )
        else:
            logger.warning(
                "--> Comment Action Likely Failed!" "\t~comment Element was not found"
            )
            return False, "commenting disabled"

    except InvalidElementStateException:
        logger.warning(
            "--> Comment Action Likely Failed!"
            "\t~encountered `InvalidElementStateException` :/"
        )
        return False, "invalid element state"

    logger.info("--> Commented: {}".format(rand_comment.encode("utf-8")))

    # get the post-comment delay time to sleep
    naply = get_action_delay("comment", Settings)
    sleep(naply)

    return True, "success"