我正在尝试拆分一个包含多个单词标签的术语,例如“#I-am-great”或“#awesome-dayofmylife”
那么我要找的输出是:
I am great
awesome day of my life
我所能做到的只有:
>>> import re
>>> name = "big #awesome-dayofmylife because #iamgreat"
>>> name = re.sub(r'#([^\s]+)', r'\1', name)
>>> print name
big awesome-dayofmylife because iamgreat
如果我被问到是否有可能的单词列表,那么答案是“否”,所以如果我能得到指导,那就太好了。任何NLP专家?
答案 0 :(得分:3)
上面的所有评论员当然都是正确的:单词之间没有空格或其他清晰分隔符的标签(特别是英语)通常是模棱两可的,无法在所有情况下正确解析。
然而,单词列表的想法实现起来相当简单,但可能会产生有用的(虽然有时是错误的)结果,所以我实现了它的快速版本:
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)
打印:
### awesome-dayofmylife
: awesome
awesome
: dayofmylife
day of my life
### iamgreat
: iamgreat
i am great
### something
: something
something
### somethingsunclear
: somethingsunclear
something sun clear
正如你所看到的,它陷入了qstebom为它设定的陷阱; - )
编辑:
上述代码的一些解释:
变量wordOr
包含所有单词的字符串,用竖线符号(|
)分隔。在正则表达式中,这意味着“其中一个单词”。
第一个findall
得到一个模式,意思是“这些单词中的一个或多个的序列”,因此它匹配“dayofmylife”之类的内容。 findall
找到所有这些序列,因此我迭代它们(for wordSequence in …
)。对于每个单词序列,我搜索序列中的每个单词(也使用findall
)并打印该单词。
答案 1 :(得分:1)
问题可以分解为几个步骤:
以下是使用此方法的一种解决方案:
# 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)
打印:
'big awe some day of my life because i am great '
您必须删除尾随空格,但这很容易。 :)