【发布时间】:2016-08-19 10:43:03
【问题描述】:
我需要将单词和含义从文件中分离出来,然后我想存储 sqlite (WORDS) 表中的每个单词及其在另一个 (MEANING) 表中的对应含义。
文件如下所示。
word 1
explanation 1
explanation 1
explanation 1
explanation 1
word 2
explanation 2
explanation 2
explanation 2
explanation 2
word 3
explanation 3
explanation 3
explanation 3
explanation 3
word 4
explanation 4
explanation 4
explanation 4
现在的问题是我无法弄清楚如何将单词和含义分成 1 - 1 个对应关系。解释行之间的空格即使拆分后也应该存在。
这是我迄今为止尝试过的示例代码。
Scanner sc = new Scanner(file);
String abbr = "";
String exp = "";
String line;
while (sc.hasNext()) {
if (!(line = sc.nextLine()).isEmpty() && !(line.startsWith(" "))) {
abbr = line;
//Debug
System.out.println(abbr);
printExp(exp);
exp = "";
} else if (line.isEmpty() || line.startsWith(" ")) {
exp += line;
}
}
用于调试目的的方法。
public static void printExp(String exp) {
if (!exp.equals("")) {
System.out.println(exp);
}
}
您可能会想到任何其他简单的解决方案,例如通过正则表达式。 非常感谢您的帮助。
【问题讨论】:
-
"文件看起来像这样。"呃,不,那是图像。文本文件中会包含文本。
-
...而且会更容易试验。
-
好的。只是为了记住文件的布局。
-
^(\w.*)((?:\n(?:$| ).*)*)之类的东西可能会帮到你。 See it here at regex101.