簡體   English   中英

有沒有辦法在 python 中加快這個速度?

[英]Is there a way to speed up this for in python?

有沒有辦法加速 python 中的這段代碼? 我需要用超過 500k 的字符串來運行它,而且時間太長了。

每個單詞都需要放入匹配的字典中。

  • example_sent_words = 500k 個字符串的列表

  • EmojiPos = 表情符號列表

  • EmojiNeg = 表情符號列表

  • OthersEmoji = 表情符號列表

emoji_pos=dict()
emoji_neg=dict()
emoji_others=dict()

for w in example_sent_words:
            if w in s_EmojiPos:
                remove_username_url.remove(w)
                if w in emoji_pos:
                    emoji_pos[w] += 1
                else:
                    emoji_pos[w] = 1
            elif w in s_EmojiNeg:
                remove_username_url.remove(w)
                if w in emoji_neg:
                    emoji_neg[w] += 1
                else:
                    emoji_neg[w] = 1
            elif w in s_OthersEmoji:
                remove_username_url.remove(w)
                if w in emoji_others:
                    emoji_others[w] += 1
                else:
                    emoji_others[w] = 1

編輯:我按照建議寫了這個:

s_AdditionalEmoji = set(AdditionalEmoji)
s_EmojiNeg = set(EmojiNeg)
s_EmojiPos = set(EmojiPos)

為了減少 memory 的使用並加快檢查速度並確保檢查每個單詞,我建議:

    word_count = len(example_sent_words)
    for i in range(word_count) :
        w = example_sent_words[0]
        if w in EmojiPos:
            example_sent_words.pop(0)
            try:
                emoji_pos[w] += 1
            except:
                emoji_pos[w] = 1
        elif w in EmojiNeg:
            example_sent_words.pop(0)
            try:
                emoji_neg[w] += 1
            except:
                emoji_neg[w] = 1
        elif w in OthersEmoji:
            example_sent_words.pop(0)
            try:
                emoji_others[w] += 1
            except:
                emoji_others[w] = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM