Wikipedysta:Wmigda

Z Wikipedii, wolnej encyklopedii
Skocz do: nawigacji, wyszukiwania
Wieża Babel
pl Polski jest językiem ojczystym tego użytkownika.
en-3 This user is able to contribute with an advanced level of English.
chem Ten wikipedysta zna terminologię stosowaną w chemii.
sport
golf
Ten wikipedysta zna terminologię stosowaną w golfie.

Useful code[edytuj | edytuj kod]

Golf[edytuj | edytuj kod]

  • LPGA GreenSheet python module (LpgaGS.py)
#!/usr/bin/python
 
import libxml2
import datetime
 
class GreenSheet:
    POSITION_DSQ = -1
    POSITION_DNS = -2
    POSITION_MC  = -3
    POSITION_WD  = -4
    POSITION_NA  = -5
    """
    attributes:
    * pid = player id
    * doc = html document
    * ctxt = xpath context
    """
    pid = None
    year = None
    doc = None
    ctxt = None
 
    def __init__(self):
        pass
 
    def __del__(self):
        if self.doc != None:
            self.doc.freeDoc()
        if self.ctxt != None:
            self.ctxt.xpathFreeContext()
        pass
 
    def fetch(self, pid, year=None):
        import urllib2
 
        self.pid = pid
        if year == None:
            # TODO: retrieve current system year
            self.year = 2008
        else:
            self.year = year
 
        options = libxml2.HTML_PARSE_RECOVER + \
                  libxml2.HTML_PARSE_NOERROR + \
                  libxml2.HTML_PARSE_NOWARNING
        url = "http://www.lpga.com/Greensheet.aspx?pid=" + str(self.pid) + \
              "&year=" + str(self.year)
 
        f = urllib2.urlopen(url)
        html = f.read()
        f.close()
 
        try:
            self.doc = libxml2.htmlReadDoc(html, "", None, options)
        except libxml2.treeError, ex:
            self.doc = None
            self.ctxt = None
            print ex
            return
        self.ctxt = self.doc.xpathNewContext()
        #print self.doc
        pass
 
    def xpathEval(self, xpath):
        """
        calls libxml2 xpath module to return set of nodes matching the provided
        xpath statement
        """
        if self.doc == None:
            return None
        return self.ctxt.xpathEval(xpath)
 
    def parseRank(self, rank):
        if rank == "N/A":
            return self.POSITION_NA, False
        elif rank[0] == 'T':
            rank = rank[1:]
            tied = True
        else:
            tied = False
        return int(rank), tied
 
    def parseMoney(self, money):
        if money[0] != "$":
            # oops.. have you put a valid argument ?
            return None
        return float(money[1:].replace(",", ""))
 
    def getPlayerName(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label1']")
        return res[0].content
 
    def getLPGAJoinYear(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label3']")
        return int(res[0].content)
 
    def getResidence(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label4']")
        return res[0].content
 
    def getTournamentsPlayed(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label5']")
        return int(res[0].content)
 
    def getSeasonMoney(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label6']")
        raw = res[0].content
        ll = raw.split(" ")
        money = self.parseMoney(ll[0])
        # strip parentheses from the rank
        rank = ll[1][1:-1]
        rank, tied = self.parseRank(rank)
        return money, rank, tied
 
    def getCareerMoney(self):
        res = self.xpathEval("//span[@id='Greensheet_performance_chart_new1_Label7']")
        raw = res[0].content
        ll = raw.split(" ")
        money = self.parseMoney(ll[0])
        # strip parentheses from the rank
        rank = ll[1][1:-1]
        rank, tied = self.parseRank(rank)
        return money, rank, tied
 
    def getScoringAvg(self):
        res = self.xpathEval("//span[@id='Greensheet_stats1_Label25']")
        rank = self.xpathEval("//span[@id='Greensheet_stats1_Label34']")
        rank, tied = self.parseRank(rank[0].content)
        return float(res[0].content), rank, tied
 
    def parsePosition(self, pos):
        tied = False
        if pos == "CUT":
            retval = self.POSITION_MC
        elif pos == "WDC":
            retval = self.POSITION_WD
        elif pos == "DNS":
            retval = self.POSITION_DNS
        elif pos == "DQ":
            retval = self.POSITION_DSQ
        else:
            if pos[-1] == "T":
                pos = pos[:-1]
                tied = True
            retval = int(pos)
        return retval, tied
 
    def parseTournamentTable(self):
        res = self.xpathEval("//span[@id='Greensheet_tourns1_Label1']")
        retval = []
        if res == None:
            return
        rows = res[0].xpathEval("tr")
        for row in rows:
            cells = row.xpathEval("td")
            # do sth with the cells
            nr = {}
            d = cells[0].content.split("/")
            nr['date'] = datetime.date(int(d[2]), int(d[0]), int(d[1]))
            nr['event'] = cells[1].content
            nr['position'] = self.parsePosition(cells[2].content)
            nr['scores'] = [int(cells[3].content), int(cells[4].content), int(cells[5].content), int(cells[6].content)]
            nr['tot_score'] = int(cells[7].content)
            nr['tot_rounds'] = int(cells[8].content)
            nr['official_money'] = self.parseMoney(cells[13].content)
            retval.append(nr)
        return retval
 
    def getCutsMade(self):
        table = self.parseTournamentTable()
        retval = 0
        for tourney in table:
            if tourney['position'][0] >= 1:
                retval += 1
        return retval
 
    def getFinishesByPlace(self, pos):
        table = self.parseTournamentTable()
        retval = 0
        pos = int(pos)
        for tourney in table:
            if tourney['position'][0] == pos:
                retval += 1
        return retval
 
    def getFinishesByRange(self, lo, hi = 1):
        table = self.parseTournamentTable()
        retval = 0
        lo = int(lo)
        hi = int(hi)
        for tourney in table:
            if tourney['position'][0] <= lo and tourney['position'][0] >= hi:
                retval += 1
        return retval
 
    def getBestFinish(self):
        table = self.parseTournamentTable()
        bf = 1000
        tied = False
        if len(table) == 0:
            return self.POSITION_NA, False
        for tourney in table:
            if tourney['position'][0] < 1:
                continue
            if tourney['position'][0] < bf:
                bf = tourney['position'][0]
                tied = tourney['position'][1]
            elif tourney['position'][0] == bf and tourney['position'][1] == False:
                tied = tourney['position'][1]
        if bf == 1000:
            return self.POSITION_NA, False
        else:
            return bf, tied
 
    pass
 
if __name__ == "__main__":
    gs = GreenSheet()
    gs.fetch(531)
 
    print gs.getPlayerName()
    print gs.getLPGAJoinYear()
    print gs.getResidence()
    print gs.getTournamentsPlayed()
    print gs.getSeasonMoney()
    print gs.getCareerMoney()
    print gs.getScoringAvg()
 
    print gs.getCutsMade()
    print gs.getFinishesByPlace(2)
    print gs.getFinishesByRange(10)
    print gs.getBestFinish()
 
    pass
  • convert player stats from LPGA site to wiki table
#!/usr/bin/python
 
import LpgaGS
import sys
 
def main(id, year):
    gs = LpgaGS.GreenSheet()
    gs.fetch(id, year)
 
    print '|-'
    print '|align="center"|%d' % int(year)
    print '|align="center"|%d' % gs.getTournamentsPlayed()
    print '|align="center"|%d' % gs.getCutsMade()
    print '|align="center"|%d' % gs.getFinishesByPlace(1)
    print '|align="center"|%d' % gs.getFinishesByPlace(2)
    print '|align="center"|%d' % gs.getFinishesByPlace(3)
    print '|align="center"|%d' % gs.getFinishesByRange(10)
    bf, tied = gs.getBestFinish()
    if bf != LpgaGS.GreenSheet.POSITION_NA:
        print '|align="center"|%s%d' % (["", "T"][int(tied)], bf)
    else:
        print '|align="center"|N/A'
    money, rank, tied = gs.getSeasonMoney()
    print '|align="right"|%d' % money
    print '|align="center"|%d' % rank
    avg, rank, tied = gs.getScoringAvg()
    print '|align="right"|%.2f' % avg
 
    pass
 
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "ERROR: please supply player ID and the year, e.g.\n> " + sys.argv[0] + " 531 2008"
        sys.exit(1)
    main(sys.argv[1], sys.argv[2])
    pass