首页 > 解决方案 > 拆分句子,处理单词并将句子重新组合在一起?

问题描述

我有一个给单词打分的功能。我有很多从句子到几页文档的文本。我被困在如何对单词进行评分并将文本恢复到原始状态附近。

这是一个例句:

"My body lies over the ocean, my body lies over the sea."

我想要制作的是以下内容:

"My body (2) lies over the ocean (3), my body (2) lies over the sea."

下面是我的评分算法的虚拟版本。我已经想出了如何获取文本,将其撕开并评分。

但是,我坚持如何将它重新组合成我需要的格式。

这是我的函数的虚拟版本:

def word_score(text):
    words_to_work_with = []
    words_to_return = []
    passed_text = TextBlob(passed_text)
    for word in words_to_work_with:
        word = word.singularize().lower()
        word = str(word)
        e_word_lemma = lemmatizer.lemmatize(word)
        words_to_work_with.append(e_word_lemma)
    for word in words to work with:
        if word == 'body':
            score = 2
        if word == 'ocean':
            score = 3
        else:
            score = None
        words_to_return.append((word,score))
    return words_to_return

我是一个相对新手,所以我有两个问题:

  1. 我怎样才能将文本重新组合在一起,以及
  2. 该逻辑应该放在函数中还是放在函数之外?

我真的很希望能够将整个片段(即句子、文档)输入到函数中并让它返回它们。

感谢你们对我的帮助!

标签: pythontextsplitnltksentence

解决方案


所以基本上,你想为每个单词分配一个分数。您提供的功能可以使用字典而不是几个if语句来改进。此外,您必须返回所有分数,而不仅仅是函数当前行为的第一个分数,因为它将在第一次迭代时返回一个整数wordwords_to_work_with所以新功能是:

def word_score(text)
    words_to_work_with = []
    passed_text = TextBlob(text)
    for word in words_to_work_with:
        word = word.singularize().lower()
        word = str(word) # Is this line really useful ?
        e_word_lemma = lemmatizer.lemmatize(word)
        words_to_work_with.append(e_word_lemma)

    dict_scores = {'body' : 2, 'ocean' : 3, etc ...}
    return [dict_scores.get(word, None)] # if word is not recognized, score is None

对于重建字符串的第二部分,我实际上会在同一个函数中执行此操作(因此这回答了您的第二个问题):

def word_score_and_reconstruct(text):
    words_to_work_with = []
    passed_text = TextBlob(text)

    reconstructed_text = ''

    for word in words_to_work_with:
        word = word.singularize().lower()
        word = str(word)  # Is this line really useful ?
        e_word_lemma = lemmatizer.lemmatize(word)
        words_to_work_with.append(e_word_lemma)

    dict_scores = {'body': 2, 'ocean': 3}
    dict_strings = {'body': ' (2)', 'ocean': ' (3)'}

    word_scores = []

    for word in words_to_work_with:
        word_scores.append(dict_scores.get(word, None)) # we still construct the scores list here

        # we add 'word'+'(word's score)', only if the word has a score
        # if not, we add the default value '' meaning we don't add anything
        reconstructed_text += word + dict_strings.get(word, '')

    return reconstructed_text, word_scores

我不保证这段代码在第一次尝试时就可以工作,我无法测试它,但它会给你主要的想法


推荐阅读