【问题标题】:How to extract text from docx file with Nodejs如何使用 Nodejs 从 docx 文件中提取文本
【发布时间】:2017-07-06 15:20:04
【问题描述】:

我想从 docx 文件中提取文本,我尝试过使用 mammoth

var mammoth = require("mammoth");
mammoth.extractRawText({path: "./doc.docx"})
    .then(function(result){
        var text = result.value; // The raw text 

        //this prints all the data of docx file
        console.log(text);

        for (var i = 0; i < text.length; i++) {
            //this prints all the data char by char in separate lines
            console.log(text[i]);
        }
        var messages = result.messages;
    })
    .done();

但这里的问题是,在这个 for 循环中,我希望逐行而不是逐字符地获取数据,请在这里帮助我,或者您知道其他方法吗?

【问题讨论】:

  • 逐行是什么意思?像 word 文档的单行,或者用换行符分隔的段落?
  • 喜欢文档@ExplosionPills 的各个行
  • 一种方法是用 "\n"s 分割你的文本!
  • 您是否运行了此代码,在控制台中,它在新行中逐字符打印数据。不需要用“\n”分割。 @tashakori
  • 不!你理解错了:-)。我的意思是用“\n”字符分割文本本身。然后你有一系列的线条! Var 行 = text.split ("\n")。然后行 [i] 表示第 i 行文本。

标签: node.js mammoth


【解决方案1】:

一种方法是获取整个文本,然后用'\n'分割:

import superagent from 'superagent';
import mammoth from 'mammoth';

const url = 'http://www.ojk.ee/sites/default/files/respondus-docx-sample-file_0.docx';

const main = async () => {

  const response = await superagent.get(url)
    .parse(superagent.parse.image)
    .buffer();

  const buffer = response.body;

  const text = (await mammoth.extractRawText({ buffer })).value;
  const lines = text.split('\n');

  console.log(lines);
};

main().catch(error => console.error(error));

【讨论】:

    【解决方案2】:

    您可以使用any-text

    用法很简单:

    var reader = require('any-text');
    
    reader.getText(`path-to-file`).then(function (data) {
      console.log(data);
    });
    

    【讨论】:

      【解决方案3】:
          var mammoth = require("mammoth");
      var path = require("path");
      
      var filePath = path.join(__dirname,'./doc.docx');
      
      mammoth.extractRawText({path: filePath})
          .then(function(result){
              var text = result.value; // The raw text
      
              //this prints all the data of docx file
              //console.log(text);
              console.log('------------------------------');
              var textLines = text.split ("\n");
      
              for (var i = 0; i < textLines.length; i++) {
                  //this prints all the data in separate lines
                  console.log(textLines[i]);
              }
              var messages = result.messages;
          })
          .done();
      

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 2015-10-06
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        相关资源
        最近更新 更多