我必须从几个 Word 文档(很多)中获取内容(一些练习的文本)并对其进行转换,以便可以将它们加载到 Javascript 应用程序中。
这些 Word 文档的内容示例如下:
<小时/>1.文字问题1
答案1
答案2
答案3
2.在问题 2 中添加一个 _ _ _ _ _ _ 或多个。
答案1
答案2
答案3
等等
<小时/>因此,一行包含问题,一行空行,然后 3 行包含可能的答案。在示例中,我提出了 2 个问题,但每个单词文档可能有 12 个以上问题。请注意,问题文本中的文字可以加下划线或加粗。也可能有空格(由几个 _ 字符表示,中间有或没有空格)。
这些 Word 文档的输出格式类似于:
var questions = [
{
label : "1.Text question 1",
options : ["answer 1", "answer 2", "answer 3"],
answer : [1] //Here I will need to set the right answer, probably manually
},
{
label : "1.Text <strong>question</strong> 2",
options : ["answer 1", "answer 2", "answer 3"],
answer : [0] //Here I will need to set the right answer, probably manually
},
etc
];
所以它是JS中的一个基本的关联数组。请注意,“label”键将以 html 格式保存问题文本(因此在示例中,有一个 <strong>
标签来反射(reflect)第二个问题中的粗体字)。
我正在寻找的是一个接受单词文档作为输入的脚本,例如示例和 输出一个 JS 文件也像我的输出示例一样(如果它是一个也可以工作的文本文件)。脚本语言最好是 PHP 或 Javascript。如果我必须对 Word 文档做一些修改来调整一些内容以使脚本更容易,那也没关系。
对我来说,主要的挑战是如何保留文本可以具有的所有文本样式(粗体、下划线、空格...),否则将它们转换为简单的 txt 文件,我想会起作用...
如有任何帮助,我们将不胜感激!
最佳答案
假设按照描述的新行,在新行处拆分并根据空白行做出选择,例如
function parse(str) {
var a = str.split('\n'), // split input and var everything
flag = 0, question = -1, qLine = 0, i,
questions = [];
for (i = 0; i < a.length; ++i) { // loop over lines
if (!a[i]) { // if blank line,
flag = 1 - flag; // flip choice
qLine = 0; // reset multi-line counter
}
else if (flag === 0) { // if question line
if (qLine === 0) { // if new question
questions.push({ // add to questions
label: a[i],
options: [],
answer: []
});
++question; // and increase question count
} else { // else multi-line question
questions[question].label += '\n' + a[i]; // add to label
}
++qLine; // either way increase multi-line counter
}
else if (flag === 1) { // if answer line
questions[question].options.push(a[i]); // add answer
}
}
return questions;
}
然后
parse('1.Text question 1\n\
\n\
answer 1\n\
answer 2\n\
answer 3\n\
\n\
2.Text question 2 with one _ _ _ _ _ _ _ or more.\n\
\n\
answer 1\n\
answer 2\n\
answer 3\n\
');
/*
[
{
"label": "1.Text question 1",
"options": [
"answer 1",
"answer 2",
"answer 3"
],
"answer": []
},
{
"label": "2.Text question 2 with one _ _ _ _ _ _ _ or more.",
"options": [
"answer 1",
"answer 2",
"answer 3"
],
"answer": []
}
]
*/
关于php - 解析word文档的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17537466/