From c91f08f07fda4960e091a842676ac00b843c76de Mon Sep 17 00:00:00 2001 From: Axpower Date: Mon, 18 Aug 2014 09:24:30 +0900 Subject: [PATCH] Adding one method to load a file from classpath I have many dev. environment and it bothers me to change path to load a file. Of course, there is a way that I don't change the path but I have to tell the way to my colleagues every time. So, I just added one method to load a file from classpath and my colleagues can avoid to create the directory in his/her dev. environment and the prod environment as well. Thanks. Ax --- src/org/nlp/vec/VectorModel.java | 57 ++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/org/nlp/vec/VectorModel.java b/src/org/nlp/vec/VectorModel.java index b941cd6..4520430 100644 --- a/src/org/nlp/vec/VectorModel.java +++ b/src/org/nlp/vec/VectorModel.java @@ -122,6 +122,63 @@ public static VectorModel loadFromFile(String path){ } + /** + * Load file from classpath + * @param path + * @return + */ + public static VectorModel loadFromClasspath(String path) { + + if (path == null || path.isEmpty()){ + throw new IllegalArgumentException("模型路径可以为null或空。"); + } + + DataInputStream dis = null; + int wordCount, layerSizeLoaded = 0; + Map wordMapLoaded = new HashMap(); + InputStream is = VectorModel.class.getResourceAsStream(path); + try { + dis = new DataInputStream(is); + wordCount = dis.readInt(); + layerSizeLoaded = dis.readInt(); + float vector; + + String key; + float[] value; + for (int i = 0; i < wordCount; i++) { + key = dis.readUTF(); + value = new float[layerSizeLoaded]; + double len = 0; + for (int j = 0; j < layerSizeLoaded; j++) { + vector = dis.readFloat(); + len += vector * vector; + value[j] = vector; + } + + len = Math.sqrt(len); + + for (int j = 0; j < layerSizeLoaded; j++) { + value[j] /= len; + } + wordMapLoaded.put(key, value); + } + + } catch (IOException ioe){ + ioe.printStackTrace(); + }finally { + try { + if (dis != null){ + dis.close(); + } + } catch (IOException ioe){ + ioe.printStackTrace(); + } + } + + return new VectorModel(wordMapLoaded, layerSizeLoaded); + + } + /** * 保存词向量模型 * @param file 模型存放路径