def from_db_cursor(cursor, **kwargs): if cursor.description: table = PrettyTable(**kwargs) table.field_names = [col[0] for col in cursor.description] for row in cursor.fetchall(): table.add_row(row) return table
def setUp(self): self.x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) self.x.add_row(["Adelaide",1295, 1158259, 600.5]) self.x.add_row(["Brisbane",5905, 1857594, 1146.4]) self.x.add_row(["Darwin", 112, 120900, 1714.7]) self.x.add_row(["Hobart", 1357, 205556, 619.5]) self.x.add_row(["Sydney", 2058, 4336374, 1214.8]) self.x.add_row(["Melbourne", 1566, 3806092, 646.9]) self.x.add_row(["Perth", 5386, 1554769, 869.4])
class FloatFormatTests(unittest.TestCase): def setUp(self): self.x = PrettyTable(["Constant", "Value"]) self.x.add_row(["Pi", pi]) self.x.add_row(["e", e]) self.x.add_row(["sqrt(2)", sqrt(2)]) def testNoDecimals(self): self.x.float_format = ".0f" self.x.caching = False assert "." not in self.x.get_string() def testRoundTo5DP(self): self.x.float_format = ".5f" string = self.x.get_string() assert "3.14159" in string assert "3.141592" not in string assert "2.71828" in string assert "2.718281" not in string assert "2.718282" not in string assert "1.41421" in string assert "1.414213" not in string def testPadWith2Zeroes(self): self.x.float_format = "06.2f" string = self.x.get_string() assert "003.14" in string assert "002.72" in string assert "001.41" in string
def setUp(self): self.x = PrettyTable(["Kanji", "Hiragana", "English"]) self.x.add_row(["神戸", "こうべ", "Kobe"]) self.x.add_row(["京都", "きょうと", "Kyoto"]) self.x.add_row(["長崎", "ながさき", "Nagasaki"]) self.x.add_row(["名古屋", "なごや", "Nagoya"]) self.x.add_row(["大阪", "おおさか", "Osaka"]) self.x.add_row(["札幌", "さっぽろ", "Sapporo"]) self.x.add_row(["東京", "とうきょう", "Tokyo"]) self.x.add_row(["横浜", "よこはま", "Yokohama"])
def stddetails(): stdid = int(input('Enter The Student Id: ')) mycursor.execute("select * from students where STD_ID='{}'".format(stdid)) results = mycursor.fetchall() t = PrettyTable([ 'STD_ID', 'STD_NAME', 'STD_GRADE', 'STD_AGE', 'STD_NUMBER', 'STD_ADDRESS' ]) for STD_ID, STD_NAME, STD_GRADE, STD_AGE, STD_NUMBER, STD_ADDRESS in results: t.add_row( [STD_ID, STD_NAME, STD_GRADE, STD_AGE, STD_NUMBER, STD_ADDRESS]) print(t)
def generate_table(self, rows): """ Generates from a list of rows a PrettyTable object. """ table = PrettyTable(**self.kwargs) for row in self.rows: if len(row[0]) < self.max_row_width: appends = self.max_row_width - len(row[0]) for i in range(1, appends): row[0].append("-") if row[1]: self.make_fields_unique(row[0]) table.field_names = row[0] else: table.add_row(row[0]) return table
def testHtmlOutput(self): t = PrettyTable(['Field 1', 'Field 2', 'Field 3']) t.add_row(['value 1', 'value2', 'value3']) t.add_row(['value 4', 'value5', 'value6']) t.add_row(['value 7', 'value8', 'value9']) result = t.get_html_string() assert result.strip() == """ <table> <tr> <th>Field 1</th> <th>Field 2</th> <th>Field 3</th> </tr> <tr> <td>value 1</td> <td>value2</td> <td>value3</td> </tr> <tr> <td>value 4</td> <td>value5</td> <td>value6</td> </tr> <tr> <td>value 7</td> <td>value8</td> <td>value9</td> </tr> </table> """.strip()
def testHtmlOutputFormated(self): t = PrettyTable(['Field 1', 'Field 2', 'Field 3']) t.add_row(['value 1', 'value2', 'value3']) t.add_row(['value 4', 'value5', 'value6']) t.add_row(['value 7', 'value8', 'value9']) result = t.get_html_string(format=True) assert result.strip() == """ <table frame="box" rules="cols"> <tr> <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th> <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 2</th> <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 3</th> </tr> <tr> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 1</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value2</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value3</td> </tr> <tr> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 4</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value5</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value6</td> </tr> <tr> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 7</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value8</td> <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value9</td> </tr> </table> """.strip()
class EmptyTableTests(CityDataTest): """Make sure the print_empty option works""" def setUp(self): CityDataTest.setUp(self) self.y = PrettyTable() self.y.field_names = ["City name", "Area", "Population", "Annual Rainfall"] def testPrintEmptyTrue(self): assert self.y.get_string(print_empty=True) != "" assert self.x.get_string(print_empty=True) != self.y.get_string(print_empty=True) def testPrintEmptyFalse(self): assert self.y.get_string(print_empty=False) == "" assert self.y.get_string(print_empty=False) != self.x.get_string(print_empty=False) def testInteractionWithBorder(self): assert self.y.get_string(border=False, print_empty=True) == ""
def setUp(self): # Row by row... self.row = PrettyTable() self.row.field_names = ["City name", "Area", "Population", "Annual Rainfall"] self.row.add_row(["Adelaide",1295, 1158259, 600.5]) self.row.add_row(["Brisbane",5905, 1857594, 1146.4]) self.row.add_row(["Darwin", 112, 120900, 1714.7]) self.row.add_row(["Hobart", 1357, 205556, 619.5]) self.row.add_row(["Sydney", 2058, 4336374, 1214.8]) self.row.add_row(["Melbourne", 1566, 3806092, 646.9]) self.row.add_row(["Perth", 5386, 1554769, 869.4]) # Column by column... self.col = PrettyTable() self.col.add_column("City name",["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"]) self.col.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386]) self.col.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]) self.col.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]) # A mix of both! self.mix = PrettyTable() self.mix.field_names = ["City name", "Area"] self.mix.add_row(["Adelaide",1295]) self.mix.add_row(["Brisbane",5905]) self.mix.add_row(["Darwin", 112]) self.mix.add_row(["Hobart", 1357]) self.mix.add_row(["Sydney", 2058]) self.mix.add_row(["Melbourne", 1566]) self.mix.add_row(["Perth", 5386]) self.mix.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]) self.mix.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4])
def from_csv(fp, field_names=None, **kwargs): fmtparams = {} for param in [ "delimiter", "doublequote", "escapechar", "lineterminator", "quotechar", "quoting", "skipinitialspace", "strict" ]: if param in kwargs: fmtparams[param] = kwargs.pop(param) if fmtparams: reader = csv.reader(fp, **fmtparams) else: dialect = csv.Sniffer().sniff(fp.read(1024)) fp.seek(0) reader = csv.reader(fp, dialect) table = PrettyTable(**kwargs) if field_names: table.field_names = field_names else: table.field_names = [x.strip() for x in next(reader)] for row in reader: table.add_row([x.strip() for x in row]) return table
def testSortSlice(self): """Make sure sorting and slicing interact in the expected way""" x = PrettyTable(["Foo"]) for i in range(20, 0, -1): x.add_row([i]) newstyle = x.get_string(sortby="Foo", end=10) assert "10" in newstyle assert "20" not in newstyle oldstyle = x.get_string(sortby="Foo", end=10, oldsortslice=True) assert "10" not in oldstyle assert "20" in oldstyle
def testHtmlBreakLine(self): t = PrettyTable(['Field 1', 'Field 2']) t.add_row(['value 1', 'value2\nsecond line']) t.add_row(['value 3', 'value4']) result = t.get_html_string(hrules=ALL) assert result.strip() == """ <table> <tr> <th>Field 1</th> <th>Field 2</th> </tr> <tr> <td>value 1</td> <td>value2<br>second line</td> </tr> <tr> <td>value 3</td> <td>value4</td> </tr> </table> """.strip()
def get_experiment_list_str(self, exp_record_dict): headers = { 'full': [ExpRecordDisplayFields.RUNS, ExpRecordDisplayFields.DURATION, ExpRecordDisplayFields.STATUS, ExpRecordDisplayFields.ARGS_CHANGED, ExpRecordDisplayFields.RESULT_STR, ExpRecordDisplayFields.NOTES], 'results': [ExpRecordDisplayFields.RESULT_STR] }[self.view_mode] if self.remove_prefix: deprefixed_ids = deprefix_experiment_ids(exp_record_dict.keys()) exp_record_dict = OrderedDict((k, v) for k, v in zip(deprefixed_ids, exp_record_dict.values())) row_func = _get_record_rows_cached if self.cache_result_string else _get_record_rows header_names = [h.value for h in headers] def remove_notes_if_no_notes(_record_rows, _record_headers): notes_column_index = _record_headers.index(ExpRecordDisplayFields.NOTES.value) if ExpRecordDisplayFields.NOTES.value in _record_headers else None # Remove the notes column if there are no notes! if notes_column_index is not None and all(row[notes_column_index]=='' or row[notes_column_index]=='-' for row in _record_rows): new_rows = [] for row in _record_rows: new_rows.append(row[:notes_column_index]+row[notes_column_index+1:]) new_headers = _record_headers[:notes_column_index]+_record_headers[:notes_column_index+1:] else: new_rows = _record_rows new_headers = _record_headers return new_rows, new_headers if self.display_format=='nested': # New Display mode if self.show_args: _, argdiff = separate_common_items([load_experiment(ex).get_args().items() for ex in exp_record_dict]) argdiff = {k: args for k, args in izip_equal(exp_record_dict.keys(), argdiff)} # Build a list of experiments and a list of records. full_headers = ['#']+header_names record_rows = [] experiment_rows = [] experiment_row_ixs = [] counter = 1 # Start at 2 because record table has the headers. for i, (exp_id, record_ids) in enumerate(exp_record_dict.items()): experiment_row_ixs.append(counter) exp_identifier = exp_id if not self.show_args else ','.join('{}={}'.format(k, v) for k, v in argdiff[exp_id]) experiment_rows.append([i, exp_identifier]) for j, record_id in enumerate(record_ids): record_rows.append([j]+row_func(record_id, headers, raise_display_errors=self.raise_display_errors, truncate_to=self.truncate_result_to, ignore_valid_keys=self.ignore_valid_keys)) counter+=1 record_rows, full_headers = remove_notes_if_no_notes(record_rows, full_headers) # Merge the experiments table and record table. if self.table_package=='tabulate': record_table_rows = tabulate(record_rows, headers=full_headers, tablefmt="pipe").split('\n') del record_table_rows[1] # Get rid of that silly line. experiment_table_rows = tabulate(experiment_rows, numalign='left').split('\n')[1:-1] # First and last are just borders longest_row = max(max(len(r) for r in record_table_rows), max(len(r) for r in experiment_table_rows)+4) if len(record_table_rows)>0 else 0 record_table_rows = [r if len(r)==longest_row else r[:-1] + ' '*(longest_row-len(r)) + r[-1] for r in record_table_rows] experiment_table_rows = [('=' if i==0 else '-')*longest_row+'\n'+r + ' '*(longest_row-len(r)-1)+'|' for i, r in enumerate(experiment_table_rows)] all_rows = [surround_with_header('Experiments', width=longest_row, char='=')] + insert_at(record_table_rows, experiment_table_rows, indices=experiment_row_ixs) + ['='*longest_row] table = '\n'.join(all_rows) else: raise NotImplementedError(self.table_package) elif self.display_format=='flat': # Display First record on same row full_headers = ['E#', 'R#', 'Experiment']+header_names rows = [] for i, (exp_id, record_ids) in enumerate(exp_record_dict.items()): if len(record_ids)==0: rows.append([str(i), '', exp_id, '<No Records>'] + ['-']*(len(headers)-1)) else: for j, record_id in enumerate(record_ids): rows.append([str(i) if j==0 else '', j, exp_id if j==0 else '']+row_func(record_id, headers, raise_display_errors=self.raise_display_errors, truncate_to=self.truncate_result_to, ignore_valid_keys=self.ignore_valid_keys)) assert len(rows[0])==len(full_headers) rows, full_headers = remove_notes_if_no_notes(rows, full_headers) if self.table_package == 'pretty_table': from prettytable.prettytable import PrettyTable table = str(PrettyTable(rows, field_names=full_headers, align='l', max_table_width=self.max_width)) elif self.table_package == 'tabulate': table = tabulate(rows, headers=full_headers) else: raise NotImplementedError(self.table_package) else: raise NotImplementedError(self.display_format) return table
class CityDataTest(unittest.TestCase): """Just build the Australian capital city data example table.""" def setUp(self): self.x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) self.x.add_row(["Adelaide",1295, 1158259, 600.5]) self.x.add_row(["Brisbane",5905, 1857594, 1146.4]) self.x.add_row(["Darwin", 112, 120900, 1714.7]) self.x.add_row(["Hobart", 1357, 205556, 619.5]) self.x.add_row(["Sydney", 2058, 4336374, 1214.8]) self.x.add_row(["Melbourne", 1566, 3806092, 646.9]) self.x.add_row(["Perth", 5386, 1554769, 869.4])
class BuildEquivelanceTest(unittest.TestCase): """Make sure that building a table row-by-row and column-by-column yield the same results""" def setUp(self): # Row by row... self.row = PrettyTable() self.row.field_names = ["City name", "Area", "Population", "Annual Rainfall"] self.row.add_row(["Adelaide",1295, 1158259, 600.5]) self.row.add_row(["Brisbane",5905, 1857594, 1146.4]) self.row.add_row(["Darwin", 112, 120900, 1714.7]) self.row.add_row(["Hobart", 1357, 205556, 619.5]) self.row.add_row(["Sydney", 2058, 4336374, 1214.8]) self.row.add_row(["Melbourne", 1566, 3806092, 646.9]) self.row.add_row(["Perth", 5386, 1554769, 869.4]) # Column by column... self.col = PrettyTable() self.col.add_column("City name",["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"]) self.col.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386]) self.col.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]) self.col.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]) # A mix of both! self.mix = PrettyTable() self.mix.field_names = ["City name", "Area"] self.mix.add_row(["Adelaide",1295]) self.mix.add_row(["Brisbane",5905]) self.mix.add_row(["Darwin", 112]) self.mix.add_row(["Hobart", 1357]) self.mix.add_row(["Sydney", 2058]) self.mix.add_row(["Melbourne", 1566]) self.mix.add_row(["Perth", 5386]) self.mix.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]) self.mix.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]) def testRowColEquivalenceASCII(self): self.assertEqual(self.row.get_string(), self.col.get_string()) def testRowMixEquivalenceASCII(self): self.assertEqual(self.row.get_string(), self.mix.get_string()) def testRowColEquivalenceHTML(self): self.assertEqual(self.row.get_html_string(), self.col.get_html_string()) def testRowMixEquivalenceHTML(self): self.assertEqual(self.row.get_html_string(), self.mix.get_html_string())
class PrintJapanestTest(unittest.TestCase): def setUp(self): self.x = PrettyTable(["Kanji", "Hiragana", "English"]) self.x.add_row(["神戸", "こうべ", "Kobe"]) self.x.add_row(["京都", "きょうと", "Kyoto"]) self.x.add_row(["長崎", "ながさき", "Nagasaki"]) self.x.add_row(["名古屋", "なごや", "Nagoya"]) self.x.add_row(["大阪", "おおさか", "Osaka"]) self.x.add_row(["札幌", "さっぽろ", "Sapporo"]) self.x.add_row(["東京", "とうきょう", "Tokyo"]) self.x.add_row(["横浜", "よこはま", "Yokohama"]) def testPrint(self): print() print(self.x)
def setUp(self): CityDataTest.setUp(self) self.y = PrettyTable() self.y.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
grupo_variaveis["qtd_msg%d" % idx] = 0 grupo_variaveis["qtd_plv%d" % idx] = 0 grupo_variaveis["qtd_img%d" % idx] = 0 for linha in f: if nomeTratado in linha: grupo_variaveis["qtd_msg%d" % idx] += 1 msgPura = regex.msgPura(linha).strip() grupo_variaveis["qtd_plv%d" % idx] += regex.contarPalavras(msgPura) grupo_variaveis["qtd_img%d" % idx] += calculo.quantasImg(msgPura) media = round( calculo.calcularMedia(grupo_variaveis["qtd_msg%d" % idx], grupo_variaveis["qtd_plv%d" % idx]), 2) grupo_variaveis["qtd_media%d" % idx] = media ##criação da tabela de output 1 zc = PrettyTable() zc.field_names = [ "Nome", "Qtd Mensagens", "Qtd Palavras", "Média", "Qtd imagens" ] for idx, nome in enumerate(dict_nomes, 1): zc.add_row([ nome, format(grupo_variaveis["qtd_msg%d" % idx], ",d"), format(grupo_variaveis["qtd_plv%d" % idx], ",d"), grupo_variaveis["qtd_media%d" % idx], format(grupo_variaveis["qtd_img%d" % idx], ",d") ]) print(zc)
def testAsciiBreakLine(self): t = PrettyTable(['Field 1', 'Field 2']) t.add_row(['value 1', 'value2\nsecond line']) t.add_row(['value 3', 'value4']) result = t.get_string(hrules=ALL) assert result.strip() == """ +---------+-------------+ | Field 1 | Field 2 | +---------+-------------+ | value 1 | value2 | | | second line | +---------+-------------+ | value 3 | value4 | +---------+-------------+ """.strip() t = PrettyTable(['Field 1', 'Field 2']) t.add_row(['value 1', 'value2\nsecond line']) t.add_row(['value 3\n\nother line', 'value4\n\n\nvalue5']) result = t.get_string(hrules=ALL) assert result.strip() == """ +------------+-------------+ | Field 1 | Field 2 | +------------+-------------+ | value 1 | value2 | | | second line | +------------+-------------+ | value 3 | value4 | | | | | other line | | | | value5 | +------------+-------------+ """.strip() t = PrettyTable(['Field 1', 'Field 2']) t.add_row(['value 1', 'value2\nsecond line']) t.add_row(['value 3\n\nother line', 'value4\n\n\nvalue5']) result = t.get_string() assert result.strip() == """ +------------+-------------+ | Field 1 | Field 2 | +------------+-------------+ | value 1 | value2 | | | second line | | value 3 | value4 | | | | | other line | | | | value5 | +------------+-------------+ """.strip()
def setUp(self): self.x = PrettyTable(["Constant", "Value"]) self.x.add_row(["Pi", pi]) self.x.add_row(["e", e]) self.x.add_row(["sqrt(2)", sqrt(2)])