今天,我正在与一个使用Java从文本文件中创建一致性的客户端一起工作。我需要做的就是颠倒一致性,从头到尾基本上重新创建文本。现在,我似乎遇到的问题是从哪里开始以及如何执行每个步骤。到目前为止,我已经尝试创建一个单词数组并遍历我的符号表并将每个键分配给该数组。然后,我最终仅从一致性中得到单词列表。由于某种原因,这个问题使我感到非常愚蠢,因为它似乎应该是一个简单的解决方案。我似乎想不出任何有效的主意来使我重新开始故事。我在这里包括了源代码:
public class InvertedConcordance {
public static ST<String, SET<Integer>> createConcordance (String[] words) {
ST<String, SET<Integer>> st = new ST<String, SET<Integer>>();
for (int i = 0; i < words.length; i++) {
String s = words[i];
if (!st.contains(s)) {
st.put(s, new SET<Integer>());
}
SET<Integer> set = st.get(s);
set.add(i);
}
return st;
}
public static String[] invertConcordance (ST<String, SET<Integer>> st) {
//This is what I have so far
//Here is what I have that doesnt work
for(String key : st.keys())
{
inv[i++] = key;
}
for(int z = 0; z< inv.length; z++)
{
System.out.println(inv[z]);
}
String[]inv = new String[st.size()];
return inv;
}
private static void saveWords (String fileName, String[] words) {
int MAX_LENGTH = 70;
Out out = new Out (fileName);
int length = 0;
for (String word : words) {
length += word.length ();
if (length > MAX_LENGTH) {
out.println ();
length = word.length ();
}
out.print (word);
out.print (" ");
length++;
}
out.close ();
}
public static void main(String[] args) {
String fileName = "data/tale.txt";
In in = new In (fileName);
String[] words = in.readAll().split("\\s+");
ST<String, SET<Integer>> st = createConcordance (words);
StdOut.println("Finished building concordance");
// write to a file and read back in (to check that serialization works)
//serialize ("data/concordance-tale.txt", st);
//st = deserialize ("data/concordance-tale.txt");
words = invertConcordance (st);
saveWords ("data/reconstructed-tale.txt", words);
}
}
最佳答案
首先-为什么要使用一些奇怪的类,例如:
组
ST
而不是内置的Java类:
组
地图
哪一个在这里?
对于您的问题,由于您声明变量inv
之后使用它,因此代码根本不应该编译:
public static String[] invertConcordance (ST<String, SET<Integer>> st) {
//This is what I have so far
//Here is what I have that doesnt work
for(String key : st.keys())
{
inv[i++] = key;
}
for(int z = 0; z< inv.length; z++)
{
System.out.println(inv[z]);
}
String[]inv = new String[st.size()];
return inv;
}
如果我正确地理解了您的想法,那么一致性仅会创建单词和集合的列表,其中包含在其上找到的索引。如果这是正确的解释,那么逆运算将是:
public static String[] invertConcordance (ST<String, SET<Integer>> st) {
//First - figure out the length of the document, which is simply the maximum index in the concordancer
int document_length = 0;
for(String key : st.keys()){
for(Integer i : st.get(key)){
if(i>document_length){
document_length=i;
}
}
}
//Create the document
String[] document = new String[document_length+1];
//Reconstruct
for(String key : st.keys()){
for(Integer i : st.get(key)){
document[i] = key;
}
}
return document;
}
我假设索引的编号从0到文档的length-1,如果实际上存储的索引从1到document'length,则应修改以下行:
String[] document = new String[document_length+1];
至
String[] document = new String[document_length];
和
document[i] = key;
至
document[i-1] = key;