python类tabulate()的实例源码

bow.py 文件源码 项目:sota_sentiment 作者: jbarnesspain 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def print_results(out_file):

    names, results = test()

    table_data = [[name] + result for name, result in zip(names, results)]
    table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f')

    if out_file:
        with open(out_file, 'a') as f:
            f.write('\n')
            f.write('+++Bag-of-words+++\n')
            f.write(table)
            f.write('\n')
    else:
        print()
        print('+++Bag-of-words with L2 regularized Logistic Regression+++')
        print(table)
cli.py 文件源码 项目:trader-bot 作者: ricco386 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def get_assets(self):
        """Assets and asset pairs availalbe at the exchange

        Get all available assets and also traiding asset pairs from the
        exchange.
        """
        table = [
            ['ASSET', 'ALTNAME', 'DECIMALS']
        ]

        for asset, props in self.kraken.get_assets().items():
            table.append([asset, props['altname'], props['decimals']])

        print(tabulate(table, headers="firstrow", numalign="right"))
        print("\n")

        table = [
            ['PAIR', 'ALTNAME', 'DECIMALS']
        ]

        for pair, props in self.kraken.get_asset_pairs().items():
            table.append([pair, props['altname'], props['pair_decimals']])

        print(tabulate(table, headers="firstrow", numalign="right"))
pandas_utils.py 文件源码 项目:labutils 作者: networks-lab 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def clip_df(df, tablefmt='html'):
    """
    Copy a dataframe as plain text to your clipboard.
    Probably only works on Mac. For format types see ``tabulate`` package
    documentation.

    :param pandas.DataFrame df: Input DataFrame.
    :param str tablefmt: What type of table?
    :return: None.
    """
    if tablefmt == 'material':
        html = tabulate.tabulate(df, headers=df.columns, tablefmt='html')
        html = html.replace('<table>', '<table class="mdl-data-table mdl-js-data-table">')
        header = '<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">\n<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">\n<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>'
        html = header + '\n' + html
    else:
        html = tabulate.tabulate(df, headers=df.columns, tablefmt=tablefmt)
    pyperclip.copy(html)
    print('Copied {} table to clipboard!'.format(tablefmt))
    return html
cli.py 文件源码 项目:TyStrings 作者: luckytianyiyan 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def lint(args):
    logger.process('Parsing Source Reference...')
    elems = Strings.parsing_elems(filename=args.file, encoding='utf8' if args.utf8 else None)
    logger.process('Check Duplicate Keys...')
    duplicates = []
    for item, count in collections.Counter([e[0] for e in elems]).items():
        if count > 1:
            duplicates.append((item, count))

    if duplicates:
        table = []
        table_file = []
        logger.info('Find the following:')
        for key, count in duplicates:
            table.append([key, count])
            for elem in elems:
                if elem[0] == key:
                    table_file.append([elem[2], elem[0], elem[1]])
        logger.info(tabulate(table, headers=['Key', 'Count'], showindex='always', tablefmt="orgtbl"))
        logger.debug('Detail:')
        logger.debug(tabulate(table_file, headers=['Line', 'Key', 'Value'], tablefmt="orgtbl"))
        logger.error('Duplicate Keys')
        exit(1)

    logger.success('lint success')
tables.py 文件源码 项目:demos 作者: dfirence 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def parse_vt_filescans( apiresults ):
    VTRES   = []
    COLUMNS = [ 'Index', 'Source', 'ScanDate', 'Hash', 'Verdict' ]
    counter = 0

    for scan in apiresults:
        for item in scan:
            counter += 1
            if item['response_code'] == 0:
                VTRES.append([ counter, 'VirusTotal', '---', item['resource'].upper(), '---' ])

            elif item['response_code'] == 1:
                VTRES.append([ counter, 'VirusTotal', item['scan_date'], item['resource'].upper(), '{}/{}'.format( item['positives'], item['total'] ) ])

    TABLE = tabulate( VTRES, headers=COLUMNS )
    return TABLE
create_delete_sddc.py 文件源码 项目:vsphere-automation-sdk-python 作者: vmware 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def create_sddc(self):
        print('\n# Example: Create a SDDC ({}) in org {}:'.
              format(self.sddc_name, self.org_id))

        provider = os.environ.get('VMC_PROVIDER', 'AWS')
        sddc_config = AwsSddcConfig(
            region='US_WEST_2', num_hosts=1, name=self.sddc_name,
            provider=provider)
        task = self.vmc_client.orgs.Sddcs.create(org=self.org_id,
                                                 sddc_config=sddc_config)
        wait_for_task(task_client=self.vmc_client.orgs.Tasks,
                      org_id=self.org_id,
                      task_id=task.id,
                      interval_sec=self.interval_sec)

        print('\n# Example: SDDC created:')
        self.sddc_id = task.resource_id
        sddc = self.vmc_client.orgs.Sddcs.get(self.org_id, self.sddc_id)
        print(tabulate([[sddc.id, sddc.name]], ["ID", "Name"]))
create_delete_sddc.py 文件源码 项目:vsphere-automation-sdk-python 作者: vmware 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def delete_sddc(self):
        print('\n# Example: Delete SDDC {} from org {}'.format(self.sddc_id,
                                                                self.org_id))
        task = self.vmc_client.orgs.Sddcs.delete(org=self.org_id,
                                                 sddc=self.sddc_id)
        wait_for_task(task_client=self.vmc_client.orgs.Tasks,
                      org_id=self.org_id,
                      task_id=task.id,
                      interval_sec=self.interval_sec)

        print('\n# Example: Remaining SDDCs:'.
              format(self.org_id))
        sddcs_list = self.vmc_client.orgs.Sddcs.list(self.org_id)

        headers = ["ID", "Name"]
        table = []
        for sddc in sddcs_list:
            table.append([sddc.id, sddc.name])
        print(tabulate(table, headers))
stalker.py 文件源码 项目:PyStalker 作者: amarlearning 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def print_in_style(catch,username) :
    table = [[1,username,catch[10:]]]
    headers = ["Sno.","Username", "Last Visit"]
    print tabulate(table, headers, tablefmt="fancy_grid")
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if(x == 1) :
        flag = 0
        call_defined_function(menu(flag))
    elif(x == 0) :
        clear()
    else :
        flag = 1
        call_defined_function(menu(flag))
test.py 文件源码 项目:IntroPython2016 作者: UWPCE-PythonCert 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def donation_list():
    # establish separate dictionary objects #
    results = collections.OrderedDict()
    donor_dict = {"Donors": []}
    totals_dict = {"Total $": []}
    # loop through donors data set and perform aggregate functions #
    for donor, donations in sorted(donors.items()):
        donor_dict["Donors"].append(donor)
        totals_dict["Total $"].append((sum(donations)))
    # combine dictionary objects into one for tabulate data input format #
    results.update(donor_dict)
    results.update(totals_dict)
    print(tabulate(results, headers="keys", tablefmt="fancy_grid", numalign="center"))


# Add donor name to list #
test.py 文件源码 项目:IntroPython2016 作者: UWPCE-PythonCert 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def report_data():
    # establish separate dictionary objects #
    results = collections.OrderedDict()
    donor_dict = {"Donors": []}
    totals_dict = {"Total $": []}
    num_results = {"Number of Donations": []}
    avg_results = {"Average Donation": []}
    # loop through donors data set and perform aggregate functions #
    for donor, donations in sorted(donors.items()):
        donor_dict["Donors"].append(donor)
        totals_dict["Total $"].append((sum(donations)))
        num_results["Number of Donations"].append(len(donations))
        avg_results["Average Donation"].append(int(numpy.mean(donations)))
    # combine dictionary objects into one for tabulate data input format #
    results.update(donor_dict)
    results.update(totals_dict)
    results.update(num_results)
    results.update(avg_results)
    print(tabulate(results, headers="keys", tablefmt="fancy_grid", numalign="center"))
    user_input()
mailroom_new.py 文件源码 项目:IntroPython2016 作者: UWPCE-PythonCert 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def donation_list():
    # establish separate dictionary objects #
    results = collections.OrderedDict()
    donor_dict = {"Donors": []}
    totals_dict = {"Total $": []}
    # loop through donors data set and perform aggregate functions #
    for donor, donations in sorted(donors.items()):
        donor_dict["Donors"].append(donor)
        totals_dict["Total $"].append((sum(donations)))
    # combine dictionary objects into one for tabulate data input format #
    results.update(donor_dict)
    results.update(totals_dict)
    print(tabulate(results, headers="keys", tablefmt="fancy_grid", numalign="center"))


# Add donor name to list #
stats.py 文件源码 项目:tableintuit 作者: Metatab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __str__(self):
        from tabulate import tabulate

        rows = []

        for name, stats in iteritems(self._stats):
            stats_dict = stats.dict
            del stats_dict['uvalues']
            #stats_dict['hist'] = text_hist(stats_dict['hist'], True)
            if not rows:
                rows.append(list(stats_dict.keys()))

            rows.append(list(stats_dict.values()))
        if rows:
            table = tabulate(rows[1:], rows[0], tablefmt='pipe')
            return 'Statistics \n' + table
        else:
            return 'Statistics: None \n'
data.py 文件源码 项目:uci-statnlp 作者: sameersingh 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def print_table(table, row_names, col_names, latex_file = None):
    """Pretty prints the table given the table, and row and col names.

    If a latex_file is provided (and tabulate is installed), it also writes a
    file containing the LaTeX source of the table (which you can \input into your report)
    """
    try:
        from tabulate import tabulate
        rows = map(lambda r,t: [r] + t, zip(row_names,table.tolist()))
        print(tabulate(rows, headers = [""] + col_names))
        if latex_file is not None:
            latex_str = tabulate(rows, headers = [""] + col_names, tablefmt="latex")
            with open(latex_file, 'w') as f:
                f.write(latex_str)
                f.close()
    except ImportError as e:
        row_format ="{:>15} " * (len(col_names) + 1)
        print(row_format.format("", *col_names))
        for row_name, row in zip(row_names, table):
            print(row_format.format(row_name, *row))
kafka_tools.py 文件源码 项目:oa_qian 作者: sunqb 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def desc_topic(client, args):
    """Print detailed information about a topic.

    :param client: KafkaClient connected to the cluster.
    :type client:  :class:`pykafka.KafkaClient`
    :param topic:  Name of the topic.
    :type topic:  :class:`str`
    """
    # Don't auto-create topics.
    if args.topic not in client.topics:
        raise ValueError('Topic {} does not exist.'.format(args.topic))
    topic = client.topics[args.topic]
    print('Topic: {}'.format(topic.name))
    print('Partitions: {}'.format(len(topic.partitions)))
    print('Replicas: {}'.format(len(topic.partitions.values()[0].replicas)))
    print(tabulate.tabulate(
        [(p.id, p.leader.id, [r.id for r in p.replicas], [r.id for r in p.isr])
         for p in topic.partitions.values()],
        headers=['Partition', 'Leader', 'Replicas', 'ISR'],
        numalign='center',
    ))
search.py 文件源码 项目:gsbot 作者: pachev 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def lookup(self, ctx, name=""):
        """Looks up a guild member by family name or character name"""
        try:
            members = Member.objects(Q(fam_name__icontains = name) | Q(char_name__icontains = name),
                                     server = ctx.message.server.id)
            rows = get_row(members, False)
            data = tabulate(rows,
                            HEADERS,
                            'simple',)

            if members.count() == 1:
                await self.bot.say(codify(data) +"\n" + members.first().gear_pic)
            else:
                for page in paginate(data):
                    await self.bot.say(page)

        except Exception as e:
            print(e)
            await self.bot.say("Something went horribly wrong")
listings.py 文件源码 项目:gsbot 作者: pachev 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def list(self,ctx,num=100):
        """List all the members and their gear score with optional limit. 
        Example. gsbot list returns first 100 by default  and gsbot list 5 first 5 sorted by
        gear score"""
        try:
            print('server,', ctx.message.server.id)
            members = Member.objects(server=ctx.message.server.id)
            print(Member.objects().first().server)
            rows = get_row(members, True, num)

            data = tabulate(rows,
                            HEADERS,
                           'simple',)

            for page in paginate(data):
                await self.bot.say(page)
        except Exception as e:
            await self.bot.say("Something went horribly wrong")
            print(e)
listings.py 文件源码 项目:gsbot 作者: pachev 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def over(self, ctx, num=400):
        """List all the members over a certain gear score"""
        try:
            members = Member.objects(gear_score__gte = num, server = ctx.message.server.id)
            rows = get_row(members,False)

            data = tabulate(rows,
                            HEADERS,
                           'simple',)

            for page in paginate(data):
                await self.bot.say(page)

        except Exception as e:
            print(e)
            await self.bot.say("Something went horribly wrong")
delete.py 文件源码 项目:gsbot 作者: pachev 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def delete(self, ctx, fam_name=''):
        """Deletes character from list. **officers can add an optional family name at the
        end to delete a certain user"""

        try:
            author = ctx.message.author
            if not fam_name:
                member = Member.objects(discord = author.id).first()
            else:
                member = Member.objects(fam_name = fam_name, server = ctx.message.server.id).first()
                roles = [u.name for u in author.roles]
                if ADMIN_USER not in roles:
                    await self.bot.say("Only officers may perform this action")
                    return
            info = [["Success Deleting User"], ["Character", member.char_name], ["Family", member.fam_name]]
            member.delete()
            await self.bot.say(codify(tabulate(info)))
        except Exception as e:
            print(e)
            await self.bot.say(codify("Error deleting user"))
telegram.py 文件源码 项目:freqtrade 作者: gcarq 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _status_table(bot: Bot, update: Update) -> None:
    """
    Handler for /status table.
    Returns the current TradeThread status in table format
    :param bot: telegram bot
    :param update: message update
    :return: None
    """
    # Fetch open trade
    trades = Trade.query.filter(Trade.is_open.is_(True)).all()
    if get_state() != State.RUNNING:
        send_msg('*Status:* `trader is not running`', bot=bot)
    elif not trades:
        send_msg('*Status:* `no active order`', bot=bot)
    else:
        trades_list = []
        for trade in trades:
            # calculate profit and send message to user
            current_rate = exchange.get_ticker(trade.pair)['bid']
            trades_list.append([
                trade.id,
                trade.pair,
                shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)),
                '{:.2f}'.format(100 * trade.calc_profit(current_rate))
            ])

        columns = ['ID', 'Pair', 'Since', 'Profit']
        df_statuses = DataFrame.from_records(trades_list, columns=columns)
        df_statuses = df_statuses.set_index(columns[0])

        message = tabulate(df_statuses, headers='keys', tablefmt='simple')
        message = "<pre>{}</pre>".format(message)

        send_msg(message, parse_mode=ParseMode.HTML)
telegram.py 文件源码 项目:freqtrade 作者: gcarq 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def _count(bot: Bot, update: Update) -> None:
    """
    Handler for /count.
    Returns the number of trades running
    :param bot: telegram bot
    :param update: message update
    :return: None
    """
    if get_state() != State.RUNNING:
        send_msg('`trader is not running`', bot=bot)
        return

    trades = Trade.query.filter(Trade.is_open.is_(True)).all()

    message = tabulate({
        'current': [len(trades)],
        'max': [_CONF['max_open_trades']]
    }, headers=['current', 'max'], tablefmt='simple')
    message = "<pre>{}</pre>".format(message)
    logger.debug(message)
    send_msg(message, parse_mode=ParseMode.HTML)


问题


面经


文章

微信
公众号

扫码关注公众号