【发布时间】: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
问题是它需要永远运行! 我怎样才能让它更快?
【问题讨论】: