多个单词的#分隔术语

2024-10-01 07:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图分割一个包含多个单词的标签的术语,比如“ŠI-am-great”或“#awesome dayofmylife”
那么我要寻找的输出是:

 I am great
 awesome day of my life

我能做到的就是:

^{pr2}$

如果我被问到我是否有一个可能的单词列表,那么答案是“不”,所以如果我能在这方面得到指导,那就太好了。有NLP专家吗?在


Tags: of答案列表my标签am单词awesome
2条回答

问题可以分为几个步骤:

  1. 用英语单词填充列表
  2. 把句子分成用空格分隔的词。在
  3. 将以“#”开头的术语视为哈希标记
  4. 对于每个标签,通过检查单词列表中是否存在单词,按最长匹配查找单词。在

以下是一种使用此方法的解决方案:

# 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)

它打印:

^{pr2}$

您将不得不删除尾随空格,但这很容易。:)

我从http://www-personal.umich.edu/~jlawler/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)并打印该单词。在

相关问题 更多 >