【问题标题】:Creating a list of sentences from a file and adding it into a dataframe从文件创建句子列表并将其添加到数据框中
【发布时间】:2021-06-15 21:29:48
【问题描述】:

我正在使用下面的代码从文件文档中创建句子列表。该函数将返回一个句子列表。


def extract_sentences(file):
    content = nlp(file)
    sentences = list(content.sents)
    return sentences

之后,我想在数据框中的“句子”列下添加每个句子。问题是在数据框中,句子看起来像一个单词列表,用逗号分隔,例如:(this, process, includes, different, stages...)。但我希望它看起来像:这个过程包括不同的阶段

【问题讨论】:

    标签: python pandas dataframe nlp spacy


    【解决方案1】:

    content.sents 是一个包含spacy.tokens.span.Span 对象的生成器对象。

    如果你想有一个字符串列表作为输出,你可以使用

    def extract_sentences(file):
        content = nlp(file)
        return [x.text for x in content.sents]
    

    注意.text 属性返回span 对象的文本表示。

    【讨论】:

      【解决方案2】:

      sentences 是每个函数的列表。 您可能希望更改您的 return 语句以返回一个字符串。 因此,完整的功能看起来像:

      def extract_sentences(file):
          content = nlp(file)
          sentences = list(content.sents)
          return " ".join(x.text for x in sentences)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-22
        • 2017-10-19
        • 2023-02-24
        • 1970-01-01
        相关资源
        最近更新 更多