Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Blatant Assignment Help

Name: Anonymous 2009-04-03 3:40

hey /prog/

I'm having some trouble with my python assignment and was wondering if you could offer some help.

The bit i am having trouble with is i have to read a bunch of names from a text file that have values after them and sort them out.

the file looks like this

steve A6 A3 A1
kevin A2 A6
nikki A1 A5 A4

what I'm trying to is sort them into nested lists (dictionaries?) or a better way if you know of one.

eg. list(0) = steve
     steve(1) = A3
     list(2(2) = A5
      etc.

but I have no idea how to go about it, I've got functions to read the files char by char or by line, and then split them at '\n' but I don't know the best way to actually sort them.

thanks for your help.

Name: Anonymous 2009-04-03 4:28

Here you go OP. I was going to make an Attribute class and have that implement its own comparable interface, upon which each name has a set of its ordered attributes, and names can be compared based on their attributes but I decided I can't be fucked.

import java.util.*;
import java.io.*;
import java.util.regex.*;
public class Names implements Comparable<Names> {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("inputfile.txt"));
        String text = "", line = "";
        while((line=br.readLine())!=null)
            text+=line+"\n";
        String[] lines = text.split("\r?\n");
        ArrayList<Names> list = new ArrayList<Names>(lines.length);
        Pattern p = Pattern.compile("([a-zA-Z]+)\\s+(([A-Z]\\d\\s*)+)\\s*",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m;
        for(int i=0; i<lines.length; i++) {
            m = p.matcher(lines[i]);
            if(m.find()) {
                list.add(new Names(m.group(1), m.group(2).split("\\s+")));
            }
        }
        Collections.sort(list);
        for(Names name : list) {
            System.out.print(name+" ");
            String[] attrs = name.getAttributes();
            for(String attr : attrs) {
                System.out.print(attr+" ");
            }
            System.out.println();
        }
    }
    private String name;
    private String[] attributes;
    public Names(String name, String... attributes) {
        this.name = name;
        this.attributes = attributes;
    }
    public int compareTo(Names o) {
        return this.name.compareTo(((Names)o).getName()); //could compare attributes here if wished
    }
    public String getName() {
        return this.name;
    }
    public String toString() {
        return this.name;
    }
    public String[] getAttributes() {
        return this.attributes;
    }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List