# Returns a list of common english terms (words)
def initialize_words():
content = None
with open('C:\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
terms = sentence.split(' ')
for term in terms:
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
wordlist = initialize_words()
sentence = "big #awesome-dayofmylife because #iamgreat"
parse_sentence(sentence, wordlist)
wordList = '''awesome day of my life because i am great something some
thing things unclear sun clear'''.split()
wordOr = '|'.join(wordList)
def splitHashTag(hashTag):
for wordSequence in re.findall('(?:' + wordOr + ')+', hashTag):
print ':', wordSequence
for word in re.findall(wordOr, wordSequence):
print word,
print
for hashTag in '''awesome-dayofmylife iamgreat something
somethingsunclear'''.split():
print '###', hashTag
splitHashTag(hashTag)
打印:
^{pr2}$
正如你所见,它落入了qstebom设置的陷阱中;-)
编辑:
对上述代码的一些解释:
变量wordOr包含由管道符号(|)分隔的所有单词的字符串。在正则表达式中表示“其中一个单词”。在
第一个findall得到一个表示“一个或多个单词序列”的模式,因此它与“dayofmylife”之类的内容相匹配。findall找到所有这些序列,所以我对它们进行迭代(for wordSequence in …)。对于每个单词序列,我搜索序列中的每个单词(也使用findall)并打印该单词。在
问题可以分为几个步骤:
以下是一种使用此方法的解决方案:
它打印:
^{pr2}$您将不得不删除尾随空格,但这很容易。:)
我从http://www-personal.umich.edu/~jlawler/wordlist得到了单词表。在
当然,上面所有的评论员都是正确的:没有空格或单词之间其他明确分隔符的标签(尤其是在英语中)常常是模棱两可的,而且在所有情况下都无法正确解析。在
然而,单词表的想法实施起来相当简单,可能会产生有用的(尽管有时是错误的)结果,因此我实现了一个快速版本:
打印:
^{pr2}$正如你所见,它落入了qstebom设置的陷阱中;-)
编辑:
对上述代码的一些解释:
变量
wordOr
包含由管道符号(|
)分隔的所有单词的字符串。在正则表达式中表示“其中一个单词”。在第一个
findall
得到一个表示“一个或多个单词序列”的模式,因此它与“dayofmylife”之类的内容相匹配。findall
找到所有这些序列,所以我对它们进行迭代(for wordSequence in …
)。对于每个单词序列,我搜索序列中的每个单词(也使用findall
)并打印该单词。在相关问题 更多 >
编程相关推荐