txt格式单词导入有道词典生词本 (java代码方式)
首先要求txt文档里单词的格式,大概需要像这种:
每行是一个单词,格式为:英文单词+空格+词性+单词意思。
注意 导出单词本的名字就是你 txt 文件的名字 我这里是 公共英语三级 单词本 建议用英文
代码
import java.io.*;
public class TextToXmlConverter {
public static void main(String[] args) {
String inputFile = "D:/xiangmu/7.22/input.txt"; // txt 文件路径和 指定的输入文件路径
convertTextToXml(inputFile);
}
private static void convertTextToXml(String inputFile) {
File input = new File(inputFile);
if (!input.exists() || !input.isFile()) {
System.err.println("File not found or not a regular file: " + inputFile);
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(input))) {
String fileName = input.getName();
String outputFileName = fileName.substring(0, fileName.indexOf('.')) + ".xml";
File outputFile = new File(input.getParent(), outputFileName);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
writer.write("<wordbook>\n");
String line;
while ((line = reader.readLine()) != null) {
writer.write(changeWords(line, fileName.substring(0, fileName.indexOf('.'))));
}
writer.write("</wordbook>\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String changeWords(String sentence, String name) {
String[] sentenceDepart = sentence.split(" ", 2);
String words = sentenceDepart[0];
String trans = sentenceDepart.length > 1 ? sentenceDepart[1] : "";
return "<item>\n" +
" <word>" + words + "</word>\n" +
" <trans>\n" +
" <![CDATA[" + trans.trim() + "]]>\n" +
" </trans>\n" +
" <tags>" + name + "</tags>\n" +
"</item>\n";
}
}