用Java解析文件的最佳方法是什么
我有一个带有标记值格式数据的文本文件。我想解析这个文件以形成一个Trie。最好的方法是什么 文件示例:(“”中的字符串是标记,“#”用于注释行。)用Java解析文件的最佳方法是什么,java,Java,我有一个带有标记值格式数据的文本文件。我想解析这个文件以形成一个Trie。最好的方法是什么 文件示例:(“”中的字符串是标记,“#”用于注释行。) 有很多方法可以做到这一点;其他人提到,这可以完成大部分工作,可能是最健壮的解决方案 另一个选择是使用 使用构造函数扫描文件 您可以选择合适的格式 可以用来提取数字 也许您可以将键/值对放入 下面是一个扫描字符串以简化操作的示例: String text = "#Hi, this is a sample file.\n" +
有很多方法可以做到这一点;其他人提到,这可以完成大部分工作,可能是最健壮的解决方案 另一个选择是使用
- 使用构造函数扫描文件
- 您可以选择合适的格式
- 可以用来提取数字
- 也许您可以将键/值对放入
字符串
以简化操作的示例:
String text =
"#Hi, this is a sample file.\n" +
"\n" +
"\"abcd\" = 12; \r\n" +
"\"abcde\"=16;\n" +
" # \"ignore\" = 13;\n" +
"\"http\" = 32; # Comment here \r" +
"\"zzz\" = 666; # Out of order! \r" +
" \"sip\" = 21 ;";
System.out.println(text);
System.out.println("----------");
SortedMap<String,Integer> map = new TreeMap<String,Integer>();
Scanner sc = new Scanner(text).useDelimiter("[\"=; ]+");
while (sc.hasNextLine()) {
if (sc.hasNext("[a-z]+")) {
map.put(sc.next(), sc.nextInt());
}
sc.nextLine();
}
System.out.println(map);
相关问题
“
,;
和空格)时的说明。简短示例:
Properties props = Properties.load(this.getClass()
.getResourceAsStream("path/to.file"));
Map<String, String> cleanedProps = new HashMap<String, String>();
for(Entry pair : props.entrySet()) {
cleanedProps.put(cleanKey(pair.getKey()),
cleanValue(pair.getValue()));
}
Properties-props=Properties.load(this.getClass())
.getResourceAsStream(“path/to.file”);
Map cleanedProps=newhashmap();
for(条目对:props.entrySet()){
cleanedProps.put(cleanKey(pair.getKey()),
cleanValue(pair.getValue());
}
请注意,在上面的解决方案中,您只需要自己实现
cleanKey()
和cleanValue()
即可。如果需要,您可能需要相应地更改数据类型,我使用字符串作为示例。这基本上是一个属性文件,我将删除标记周围的“字符串”,然后使用Properties类加载文件。最自然的方式可能是:
void doParse() {
String text =
"#Hi, this is a sample file.\n"
+ "\"abcd\" = 12;\n"
+ "\"abcde\" = 16;\n"
+ "#More comment\n"
+ "\"http\" = 32;\n"
+ "\"sip\" = 21;";
Matcher matcher = Pattern.compile("\"(.+)\" = ([0-9]+)").matcher(text);
while (matcher.find()) {
String txt = matcher.group(1);
int val = Integer.parseInt(matcher.group(2));
System.out.format("parsed: %s , %d%n", txt, val);
}
}
什么是Trie?如果您指的是树,则此数据不在树结构中。作业标记?@Byron A Trie是一种类似于树的数据结构。见@Hank谢谢。我以前没听说过那个数据结构器。@Byron它有点晦涩难懂。我想我还没有见过一个“在野外”,因为它们并不是真正针对我的领域。感谢你用这个新类启发我。或者简化源文件,使其不包含这些额外的字符。;)他给了我们要处理的输入,我只是在处理我得到的。我想这仍然会在注释为
#
的行中找到一个键/值对。
Properties props = Properties.load(this.getClass()
.getResourceAsStream("path/to.file"));
Map<String, String> cleanedProps = new HashMap<String, String>();
for(Entry pair : props.entrySet()) {
cleanedProps.put(cleanKey(pair.getKey()),
cleanValue(pair.getValue()));
}
void doParse() {
String text =
"#Hi, this is a sample file.\n"
+ "\"abcd\" = 12;\n"
+ "\"abcde\" = 16;\n"
+ "#More comment\n"
+ "\"http\" = 32;\n"
+ "\"sip\" = 21;";
Matcher matcher = Pattern.compile("\"(.+)\" = ([0-9]+)").matcher(text);
while (matcher.find()) {
String txt = matcher.group(1);
int val = Integer.parseInt(matcher.group(2));
System.out.format("parsed: %s , %d%n", txt, val);
}
}