Использование данных матчей премьер-лиги CSV для обновления значения объекта Java и возврата к CSV - PullRequest
0 голосов
/ 22 января 2019

Я новичок в Java и пытаюсь манипулировать некоторыми данными футбольных матчей, чтобы получить более глубокое понимание результатов.Мне удалось получить его для чтения из CSV, и я могу получить отдельные значения.Формат CSV примерно такой: около 400 строк:

Arsenal,Leicester,4,3,H  
Brighton,Man City,0,2,A
Chelsea,Burnley,2,3,A
Crystal Palace,Huddersfield,0,3,A
Everton,Stoke,1,0,H
Southampton,Swansea,0,0,D

Я боролся за то, чтобы извлечь домашнюю команду и выездные команды (объекты и не уверены, как сопоставить строку из CSV с ними):текущие очки, цель в чемпионате, разница между матчами подряд в excel (я планирую использовать искусственную нейронную сеть для прогнозирования совпадений на основе этих данных), затем я хотел бы сопоставлять и обновлять правильный объект каждой команды egif home teamАрсенал, и они выигрывают 2: 0 Обновление команды Арсенал (), чтобы получить еще 3 очка, еще 2 забитых мяча, обновить положение в таблице лиги.Как только это будет сделано, он прочитает следующий результат и повторите.Я знаю, что это много, но я действительно борюсь с этими частями, поэтому буду очень признателен за помощь новичку в Java.Вот мой текущий код:

InputHere.java:

package BasicP;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class InputHere {

    public static void main(String[] args) {
        List<Match> matches = new ArrayList<>();
        Path logFile = Paths.get("C:\\Users\\Lewys\\Documents", "FinalofFootballDataws.csv");

        try (BufferedReader read
                = Files.newBufferedReader(logFile, StandardCharsets.US_ASCII)) {
            String firstLine = read.readLine();
            while (firstLine != null) {
                String[] variables = firstLine.split(","); 
                String homeName = variables[0];
                String awayName = variables[1];
                String strHomeScore = variables[2];
                String strAwayScore = variables[3];
                int homeScore = Integer.parseInt(strHomeScore);
                int awayScore = Integer.parseInt(strAwayScore);

                firstLine = read.readLine();
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }

        return;
    }

}

Team.java:

public class Team {

    private String teamName;
    private int numberWin;
    private int numberDraw;
    private int numberLoss;
    private int matchesPlayed;
    private int points;
    private int goalsScored;
    private int goalsConceded;
    private int tablePosition;

    public Team(String teamName, int numberWin, int numberDraw,
                int numberLoss, int matchesPlayed, int points,
                int goalsScored, int goalsConceded, int tablePosition) {

    }

    public int getNumberWin() {
        return numberWin;
    }

    public int getNumberDraw() {
        return numberDraw;
    }

    public int getNumberLoss() {
        return numberLoss;
    }

    public int getMatchesPlayed() {
        return matchesPlayed;
    }

    public int getPoints() {
        return points;
    }

    public int getGoalsScored() {
        return goalsScored;
    }

    public int getGoalsConceded() {
        return goalsConceded;
    }

    public int getTablePosition() {
        return tablePosition;
    }

    public void setNumberWin(int i) {
        numberWin = numberWin + i;
    }

    public void setNumberDraw(int i) {
        numberDraw = numberDraw + i;
    }

    public void setNumberLoss(int i) {
        numberLoss = numberLoss + i;
    }

    public void setMatchesPlayed(int i) {
        matchesPlayed = matchesPlayed + i;
    }

    public void setPoints(int i) {
        points = points + i;
    }

    public void setGoalsScored(int i) {
        goalsScored = goalsScored + i;
    }

    public void setGoalsConceded(int i) {
        goalsConceded = goalsConceded + i;
    }

    public void settablePosition(int i) {
        tablePosition = i;
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
}

1 Ответ

0 голосов
/ 22 января 2019

Я пытаюсь решить вашу проблему. Не забудьте написать CSVReader, но я предлагаю вам попробовать использовать специальную библиотеку, чтобы лучше управлять всеми форматами CSV.

public class FootballMatchCSVReader {

    public List<FootballMatch> read(String filePath) throws IOException {
        return readAllLines(filePath).stream().map(line -> mapToFootballMatch(line.split(","))).collect(toList());
    }

    private List<String> readAllLines(String filePath) throws IOException {
        return Files.readAllLines(Paths.get(filePath));
    }

    private FootballMatch mapToFootballMatch(String[] args) {
        return new FootballMatch(args[0],args[1],Integer.valueOf(args[2]),Integer.valueOf(args[3]),args[4].charAt(0));
    }
}

Это возвращает список FootballMatch

public class FootballMatch {

    private String homeTeam;
    private String awayTeam;
    private int homeTeamScore;
    private int awayTeamScore;
    private char finalResult;

    public FootballMatch(String homeTeam, String awayTeam, int homeTeamScore, int awayTeamScore, char winner) {
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
        this.homeTeamScore = homeTeamScore;
        this.awayTeamScore = awayTeamScore;
        this.finalResult = winner;
    }

    public String getHomeTeam() {
        return homeTeam;
    }

    public void setHomeTeam(String homeTeam) {
        this.homeTeam = homeTeam;
    }

    public String getAwayTeam() {
        return awayTeam;
    }

    public void setAwayTeam(String awayTeam) {
        this.awayTeam = awayTeam;
    }

    public int getHomeTeamScore() {
        return homeTeamScore;
    }

    public void setHomeTeamScore(int homeTeamScore) {
        this.homeTeamScore = homeTeamScore;
    }

    public int getAwayTeamScore() {
        return awayTeamScore;
    }

    public void setAwayTeamScore(int awayTeamScore) {
        this.awayTeamScore = awayTeamScore;
    }

    public char getFinalResult() {
        return finalResult;
    }

    public void setFinalResult(char finalResult) {
        this.finalResult = finalResult;
    }

    @Override
    public String toString() {
        return "FootballMatch{" +
                "homeTeam='" + homeTeam + '\'' +
                ", awayTeam='" + awayTeam + '\'' +
                ", homeTeamScore=" + homeTeamScore +
                ", awayTeamScore=" + awayTeamScore +
                ", finalResult=" + finalResult +
                '}';
    }
}

Теперь я пишу FootballMatchStatisticsEngine, который вычисляет TeamStatistic для каждого матча

public class TeamStatistic {

    private String teamName;
    private int numberWin;
    private int numberDraw;
    private int numberLoss;
    private int matchesPlayed;
    private int points;
    private int goalsScored;
    private int goalsConceded;
    private int tablePosition;

    public TeamStatistic(String teamName, int numberWin, int numberDraw, int numberLoss, int matchesPlayed, int points, int goalsScored, int goalsConceded, int tablePosition) {
        this.teamName = teamName;
        this.numberWin = numberWin;
        this.numberDraw = numberDraw;
        this.numberLoss = numberLoss;
        this.matchesPlayed = matchesPlayed;
        this.points = points;
        this.goalsScored = goalsScored;
        this.goalsConceded = goalsConceded;
        this.tablePosition = tablePosition;
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }

    public int getNumberWin() {
        return numberWin;
    }

    public void setNumberWin(int numberWin) {
        this.numberWin = numberWin;
    }

    public int getNumberDraw() {
        return numberDraw;
    }

    public void setNumberDraw(int numberDraw) {
        this.numberDraw = numberDraw;
    }

    public int getNumberLoss() {
        return numberLoss;
    }

    public void setNumberLoss(int numberLoss) {
        this.numberLoss = numberLoss;
    }

    public int getMatchesPlayed() {
        return matchesPlayed;
    }

    public void setMatchesPlayed(int matchesPlayed) {
        this.matchesPlayed = matchesPlayed;
    }

    public int getPoints() {
        return points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    public int getGoalsScored() {
        return goalsScored;
    }

    public void setGoalsScored(int goalsScored) {
        this.goalsScored = goalsScored;
    }

    public int getGoalsConceded() {
        return goalsConceded;
    }

    public void setGoalsConceded(int goalsConceded) {
        this.goalsConceded = goalsConceded;
    }

    public int getTablePosition() {
        return tablePosition;
    }

    public void setTablePosition(int tablePosition) {
        this.tablePosition = tablePosition;
    }

    @Override
    public String toString() {
        return "TeamStatistic{" +
                "teamName='" + teamName + '\'' +
                ", numberWin=" + numberWin +
                ", numberDraw=" + numberDraw +
                ", numberLoss=" + numberLoss +
                ", matchesPlayed=" + matchesPlayed +
                ", points=" + points +
                ", goalsScored=" + goalsScored +
                ", goalsConceded=" + goalsConceded +
                ", tablePosition=" + tablePosition +
                '}';
    }
}

public class FootballMatchStatisticsEngine {

    public List<TeamStatistic> computeTeamStatistics(List<FootballMatch> footballMatches) {
        List<TeamStatistic> teamStatistics = getTeamStatistics(footballMatches);
        updatePosition(teamStatistics);
        return teamStatistics;
    }

    private void updatePosition(List<TeamStatistic> teamStatistics) {
        /*
        This function apply the relative table position to each TeamStatistics.
         */
               IntStream.range(0,teamStatistics.size()).forEach(i -> teamStatistics.get(i).setTablePosition(i+1));
    }

    private List<TeamStatistic> getTeamStatistics(List<FootballMatch> footballMatches) {
        /*
        The flat operation explode each match into two different TeamStatistics. One for home team and one for away team.
        After I compute the groupBy operation over team name and reduce the resulting list of Team statistics sumurizing her data.
         */
        return footballMatches
                .stream()
                .flatMap(fm -> footballMatchtoTeamStatistics(fm).stream())
                .collect(groupingBy(TeamStatistic::getTeamName, reducing(getTeamStatisticReduceOperation())))
                .values().stream().map(Optional::get)
                .sorted(comparingInt(TeamStatistic::getPoints).reversed())
                .collect(Collectors.toList());
    }

    private BinaryOperator<TeamStatistic> getTeamStatisticReduceOperation() {
        return (x, y) ->
                new TeamStatistic(
                        x.getTeamName(),
                        x.getNumberWin() + y.getNumberWin(),
                        x.getNumberDraw() + y.getNumberDraw(),
                        x.getNumberLoss() + y.getNumberLoss(),
                        x.getMatchesPlayed() + y.getMatchesPlayed(),
                        x.getPoints() + y.getPoints(),
                        x.getGoalsScored() + y.getGoalsScored(),
                        x.getGoalsConceded() + y.getGoalsConceded(), 0);
    }

    private List<TeamStatistic> footballMatchtoTeamStatistics(FootballMatch footballMatch) {
        return Arrays.asList(
                new TeamStatistic(
                        footballMatch.getHomeTeam(),
                        footballMatch.getFinalResult() == 'H' ? 1 : 0,
                        footballMatch.getFinalResult() == 'D' ? 1 : 0,
                        footballMatch.getFinalResult() == 'A' ? 1 : 0,
                        1,
                        footballMatch.getFinalResult() == 'H' ? 3 : footballMatch.getFinalResult() == 'D' ? 1 : 0,
                        footballMatch.getHomeTeamScore(),
                        footballMatch.getAwayTeamScore(),
                        0),
                new TeamStatistic(
                        footballMatch.getAwayTeam(),
                        footballMatch.getFinalResult() == 'A' ? 1 : 0,
                        footballMatch.getFinalResult() == 'D' ? 1 : 0,
                        footballMatch.getFinalResult() == 'H' ? 1 : 0,
                        1,
                        footballMatch.getFinalResult() == 'A' ? 3 : footballMatch.getFinalResult() == 'D' ? 1 : 0,
                        footballMatch.getAwayTeamScore(),
                        footballMatch.getHomeTeamScore(),
                        0)
        );
    }

}

Для проверки этого кода я пишу файл со следующими строками:

Arsenal,Leicester,4,3,H
Man City,Leicester,2,1,H
Brighton,Man City,0,2,A
Chelsea,Arsenal,0,2,A
Chelsea,Burnley,2,3,A
Crystal Palace,Huddersfield,0,3,A
Everton,Stoke,1,0,H
Southampton,Swansea,0,0,D

работает по следующему коду

    FootballMatchCSVReader reader = new FootballMatchCSVReader();
        FootballMatchStatisticsEngine statisticsEngine = new FootballMatchStatisticsEngine();
        try {
            List<FootballMatch> footbalMatches = reader.read("src/test/resources/input.txt");
            List<TeamStatistic> teamStatistics = statisticsEngine.computeTeamStatistics(footbalMatches);
            teamStatistics.forEach(t -> System.out.println(t));
        } catch (IOException e) {
            e.printStackTrace();
        }

Это вывод

TeamStatistic{teamName='Arsenal', numberWin=2, numberDraw=0, numberLoss=0, matchesPlayed=2, points=6, goalsScored=6, goalsConceded=3, tablePosition=1}
TeamStatistic{teamName='Man City', numberWin=2, numberDraw=0, numberLoss=0, matchesPlayed=2, points=6, goalsScored=4, goalsConceded=1, tablePosition=2}
TeamStatistic{teamName='Huddersfield', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=3, goalsConceded=0, tablePosition=3}
TeamStatistic{teamName='Everton', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=1, goalsConceded=0, tablePosition=4}
TeamStatistic{teamName='Burnley', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=3, goalsConceded=2, tablePosition=5}
TeamStatistic{teamName='Southampton', numberWin=0, numberDraw=1, numberLoss=0, matchesPlayed=1, points=1, goalsScored=0, goalsConceded=0, tablePosition=6}
TeamStatistic{teamName='Swansea', numberWin=0, numberDraw=1, numberLoss=0, matchesPlayed=1, points=1, goalsScored=0, goalsConceded=0, tablePosition=7}
TeamStatistic{teamName='Stoke', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=1, tablePosition=8}
TeamStatistic{teamName='Crystal Palace', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=3, tablePosition=9}
TeamStatistic{teamName='Brighton', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=2, tablePosition=10}
TeamStatistic{teamName='Chelsea', numberWin=0, numberDraw=0, numberLoss=2, matchesPlayed=2, points=0, goalsScored=2, goalsConceded=5, tablePosition=11}
TeamStatistic{teamName='Leicester', numberWin=0, numberDraw=0, numberLoss=2, matchesPlayed=2, points=0, goalsScored=4, goalsConceded=6, tablePosition=12}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...