我已经为此苦苦挣扎了几天,我想知道也许有人可以帮助我。
我想要完成的是处理一个包含一组问题和答案的文本文件。文件的内容(.doc 或 .docx)如下所示:
Document Name
1. Question one:
a. Answer one to question one
b. Answer two to question one
c. Answer three to question one
2. Question two:
a. Answer one to question two
c. Answer two to question two
e. Answer three to question two
到目前为止我尝试过的是:
通过 Apache POI 读取文档内容,如下所示:
fis = new FileInputStream(new File(FilePath));
XWPFDocument doc = new XWPFDocument(fis);
XWPFWordExtractor extract = new XWPFWordExtractor(doc);
String extractorText = extract.getText();
所以,到目前为止,我已经掌握了文档的内容。接下来,我尝试创建一个正则表达式模式,该模式将匹配问题开头的数字和点(1. , 12.)并继续直到它与冒号匹配:
Pattern regexPattern = Pattern.compile("^(\\d|\\d\\d)+\\.[^:]+:\\s*$", Pattern.MULTILINE);
Matcher regexMatcher = regexPattern.matcher(extractorText);
但是,当我尝试遍历结果集时,我找不到任何问题文本:
while (regexMatcher.find()) {
System.out.println("Found");
for (int i = 0; i < regexMatcher.groupCount() - 2; i += 2) {
map.put(regexMatcher.group(i + 1), regexMatcher.group(i + 2));
System.out.println("#" + regexMatcher.group(i + 1) + " >> " + regexMatcher.group(i + 2));
}
}
由于我是 Java 新手,我不确定我哪里出错了,希望有人能帮助我。
此外,如果有人有更好的方法来创建带有问题和相关答案的地图,我们将不胜感激。
先感谢您。
编辑:我正在尝试获取类似 Map 的内容,其中将包含键(问题文本)和另一个字符串列表,这些字符串将表示与该问题相关的一组答案,例如:
Map<String, List<String>> desiredResult = new HashMap<>();
desiredResult.entrySet().forEach((entry) -> {
String questionText = entry.getKey();
List<String> answersList = entry.getValue();
System.out.println("Now at question: " + questionText);
answersList.forEach((answerText) -> {
System.out.println("Now at answer: " + answerText);
});
});
这将生成以下输出:
Now at question: 1. Question one:
Now at answer: a. Answer one to question one
Now at answer: b. Answer two to question one
Now at answer: c. Answer three to question one
相关分类