【问题标题】:How to read attributes from an arff file from scratch in java?如何在java中从头开始读取arff文件中的属性?
【发布时间】:2020-03-18 11:02:10
【问题描述】:

我正在尝试从头开始读取此作业的 arff 文件。我觉得我做错了。例如,假设我有这条线

@attribute 'habitat' { 'd', 'g', 'l', 'm', 'p', 'u', 'w'}

我想检查它是否是一个属性,然后获取属性名称,然后将实例添加到列表中。到目前为止,我正在这样做。 (st 是我正在从文件中读取的当前行)

st=st.replaceAll("'", "");
String[] token = st.split(" ");
if(token[0].trim().equals("@attribute")) {
   Attribute a=new Attribute(token[1]);
}

我不确定如何读取实例,因为我根据空格拆分它,所以实例拆分错误。我觉得我要读错这个文件 这是我的属性类

public class Attribute {
public String name;
public LinkedList<Instance> instanceList=new LinkedList<Instance>();
}

有什么想法吗?

【问题讨论】:

  • 什么是Instance
  • 这是属性可以是什么,所以这里是:'d','g','l','m','p','u','w',你可以为简单起见,假设链表是字符串列表
  • 好的,我有一个解决方案检查这里ideone.com/RjygYE
  • results() 不是模式类中的方法?
  • 该解决方案应该适用于 Java9+

标签: java arff


【解决方案1】:

这是怎么做的:

你的属性类

class Attribute {
    private String name;
    private LinkedList<String> instanceList;

    public Attribute(String name, LinkedList<String> instanceList) {
        this.name = name;
        this.instanceList = instanceList;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LinkedList<String> getInstanceList() {
        return instanceList;
    }

    public void setInstanceList(LinkedList<String> instanceList) {
        this.instanceList = instanceList;
    }

    @Override
    public String toString() {
        return "Attribute{" +
                "name='" + name + '\'' +
                ", instanceList=" + instanceList +
                '}';
    }
}

你的主要课程:

     String str = "@attribute 'habitat' { 'd', 'g', 'l', 'm', 'p', 'u', 'w'}";
     Pattern pattern = Pattern.compile("@attribute '(.*?)' \\{\\s*(.*?)\\s*\\}");
     List<Attribute> list = new ArrayList<>();
     // in case you would like to ignore case sensitivity,
     // you could use this statement:
     // Pattern pattern = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(str);
     // check all occurance
     while (matcher.find()) {
                list.add(new Attribute(matcher.group(1),
                        new LinkedList<>(Arrays.asList(matcher.group(2).replaceAll("[',]", "").trim().split("\\s+"))))
         );
            }
     System.out.println(list);

输出:

[Attribute{name='habitat', instanceList=[d, g, l, m, p, u, w]}]

【讨论】:

  • 很高兴你没有 Java9 :) +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 2012-04-14
  • 2023-03-25
相关资源
最近更新 更多