【问题标题】:Faster de-merge of all hashtags更快地取消合并所有主题标签
【发布时间】:2018-05-16 12:26:17
【问题描述】:

我想从 Twitter 数据集中取消合并 hastags。例如:“#sunnyday”将是“晴天”。

我找到了以下代码: 该代码找到了hastags并查看了一个名为“wordlist.txt”的文件,这是一个巨大的txt文件,其中包含很多匹配单词的单词。

文本。文件可以在这里下载: http://www-personal.umich.edu/~jlawler/wordlist

来源:Term split by hashtag of multiple words

我对其进行了一些修改,以确保它在句子为空的情况下有效:“”

# Returns a list of common english terms (words)
def initialize_words():
    content = None
    with open('wordlist.txt') as f: # A file containing common english words
        content = f.readlines()
    return [word.rstrip('\n') for word in content]


def parse_sentence(sentence, wordlist):
    new_sentence = "" # output 
    # MODIFICATION: If the sentence is not empty
    if sentence != '':   
        terms = sentence.split(' ')
        for term in terms:
            # MODIFICATION: If the term is not empty
            if term != '':
                if term[0] == '#': # this is a hashtag, parse it
                    new_sentence += parse_tag(term, wordlist)
                else: # Just append the word
                    new_sentence += term
                new_sentence += " "

    return new_sentence 


def parse_tag(term, wordlist):
    words = []
    # Remove hashtag, split by dash
    tags = term[1:].split('-')
    for tag in tags:
        word = find_word(tag, wordlist)    
        while word != None and len(tag) > 0:
            words.append(word)            
            if len(tag) == len(word): # Special case for when eating rest of word
                break
            tag = tag[len(word):]
            word = find_word(tag, wordlist)
    return " ".join(words)


def find_word(token, wordlist):
    i = len(token) + 1
    while i > 1:
        i -= 1
        if token[:i] in wordlist:
            return token[:i]
    return None 

问题是它需要永远运行! 我怎样才能让它更快?

【问题讨论】:

    标签: python twitter hashtag


    【解决方案1】:

    为您的wordlist 变量使用set 而不是list

    这将是一个巨大的性能改进,因为使用list,您需要(可能)扫描整个单词列表,所以它是O(n)。对于set,它是O(1),因为通过计算项目的哈希并将其用作后备存储的索引来检查成员资格。

    【讨论】:

      猜你喜欢
      • 2014-12-25
      • 1970-01-01
      • 2012-12-03
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多