如何使用 Nodejs 从 docx 文件中提取文本



我想从docx文件中提取文本,我尝试使用猛犸象

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 循环中,我想要逐行数据而不是逐个字符,请在这里帮助我,或者您知道任何其他方法吗?

一种方法是获取整个文本,然后按'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));

您可以使用任何文本

用法是相似的:

var reader = require('any-text');
reader.getText(`path-to-file`).then(function (data) {
console.log(data);
});
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();

最新更新