• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python texttable.Texttable类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中texttable.Texttable的典型用法代码示例。如果您正苦于以下问题:Python Texttable类的具体用法?Python Texttable怎么用?Python Texttable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Texttable类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getAuccuracy

def getAuccuracy( train, testSet, k ):
	totalCount = len(testSet)
	correctCount = 0.0;

	# Init ConfusionMatrix
	confusionMatrix = { }
	for i in featuresList:
		for j in featuresList:
			confusionMatrix[ (i,j) ] = 0

	for i in range(len(testSet)):
		predition = getPrediction( getDistancesOfKSimilarSets( train, testSet[i], k ) )
		if predition == testSet[i][-1]:
			correctCount+=1;
		confusionMatrix[ testSet[i][-1], predition ] += 1

	print "Confusion Matrix"
	from texttable import Texttable
	table=[]
	row=[""]
	row.extend(featuresList)
	table.append(row)
	for i in featuresList:
		row=[i]
		for j in featuresList:
			row.append( confusionMatrix[ (i,j) ])
		table.append(row)
	T=Texttable();
	T.add_rows(table)
	print T.draw();

	return correctCount*1.0/totalCount;
开发者ID:prabhakar9885,项目名称:Statistical-Methods-in-AI,代码行数:32,代码来源:kthNearestNeighbour_randomSampling.py


示例2: __repr__

 def __repr__(self):
   t = Texttable()
   
   for rowId in range(0,self.size[0]):
     rowDetails = []
     for cellId in range(0,self.size[1]):
       cell = self.cellAtLocation(cellId,rowId)
       
       color = {
         "free":   bcolors.WHITE,
         "mine":   bcolors.PURPLE,
         "theirs": bcolors.RED
       }[cell.getState()]
       
       rowDetails.append(
         get_color_string(color, cell)
       )
     
     t.add_row(rowDetails)
   
   return "\n".join([
     t.draw(),
     self.board,
     self.state
   ])
开发者ID:YoSmudge,项目名称:goatpress-smudgebot,代码行数:25,代码来源:player.py


示例3: print_deploy_header

def print_deploy_header():
    table = Texttable(200)
    table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t", "t", "t"])
    table.header(
        ["Deployment name", "Deployment ID", "Cloud provider", "Region", "Hostname", "Source type", "Source ID",
         "Source name", "Status"])
    return table
开发者ID:cinlloc,项目名称:hammr,代码行数:7,代码来源:deployment_utils.py


示例4: format_table

def format_table(table, format='csv', outputstream=sys.stdout, **extra_options):
    """table can be a table from dict_to_table() or a dictionary.
    The dictionary can have either a single value as a key (for a
    one-dimensional table) or 2-tuples (for two-dimensional tables).
    format is currently one of csv, tsv, tex, texbitmap, or asciiart.
    Values for texbitmap should be floats between 0 and 1 and the output
    will be the TeX code for a large-pixeled bitmap."""
    if isinstance(table, dict):
        table = dict_to_table(table)

    if format in ('csv', 'tsv'):
        import csv
        dialect = {'csv' : csv.excel, 'tsv' : csv.excel_tab}[format]
        writer = csv.writer(outputstream, dialect=dialect)
        for row in table:
            writer.writerow(row)
    elif format == 'tex':
        import TeXTable
        print >>outputstream, TeXTable.texify(table, has_header=True)
    elif format == 'texbitmap':
        import TeXTable
        extra_options.setdefault('has_header', True)
        print >>outputstream, TeXTable.make_tex_bitmap(table, **extra_options)
    elif format == 'asciiart':
        from texttable import Texttable
        texttable = Texttable(**extra_options)
        texttable.add_rows(table)
        print >>outputstream, texttable.draw()
    else:
        raise ValueError("Unsupported format: %r (supported formats: %s)" % \
            (format, ' '.join(supported_formats)))
开发者ID:TPNguyen,项目名称:ucleed,代码行数:31,代码来源:FigUtil.py


示例5: render_schemas_as_table

def render_schemas_as_table(schemas, display_heading=True):
    """
    Returns ASCII table view of schemas.

    :param schemas: The schemas to be rendered.
    :type schemas: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Schema\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (schemas.url, schemas.total_count,
           schemas.limit, schemas.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l', 'l', 'l', 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm', 'm', 'm', 'm', 'm'])
    table.header(["ID", "Name", "Namespace", "Type", "Subtype", "Immutable",
                  "Hidden"])
    for schema in schemas:
        table.add_row([schema.id, schema.name, schema.namespace,
                       schema.type, schema.subtype or '',
                       str(bool(schema.immutable)), str(bool(schema.hidden))])
    return heading + table.draw() + "\n"
开发者ID:wettenhj,项目名称:mytardisclient,代码行数:33,代码来源:views.py


示例6: render_instruments_as_table

def render_instruments_as_table(instruments, display_heading=True):
    """
    Returns ASCII table view of instruments.

    :param instruments: The instruments to be rendered.
    :type instruments: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Instrument\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (instruments.url, instruments.total_count,
           instruments.limit, instruments.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm'])
    table.header(["ID", "Name", "Facility"])
    for instrument in instruments:
        table.add_row([instrument.id, instrument.name, instrument.facility])
    return heading + table.draw() + "\n"
开发者ID:wettenhj,项目名称:mytardisclient,代码行数:30,代码来源:views.py


示例7: _create_website

def _create_website(args):
    api = _login(args)
    if len(args.site_apps) % 2:
        print('Error: invalid site applications array')
        print('Array items should be pairs of application name and URL path')
        print('Example: django_app / django_app_media /media')
        return
    else:
        site_apps = zip(args.site_apps[::2], args.site_apps[1::2])
        for site_app in site_apps:
            app_name, app_url = site_app
            if not VALID_SYMBOLS.match(app_name):
                print('Error: %s is not a valid app name' % app_name)
                print('use A-Z a-z 0-9 or uderscore symbols only')
                return

            if not VALID_URL_PATHS.match(app_url):
                print('Error: %s is not a valid URL path' % app_url)
                print('must start with / and only regular characters, . and -')
                return

        response = api.create_website(args.website_name, args.ip, args.https, \
            args.subdomains, *site_apps)

        print('Web site has been created:')
        table = Texttable(max_width=140)
        table.add_rows([['Param', 'Value']] + [[key, value] for key, value in response.items()])
        print(table.draw())
开发者ID:kevwilde,项目名称:django-webfaction,代码行数:28,代码来源:webfactionctl.py


示例8: output_table_list

    def output_table_list(tables):
        terminal_size = get_terminal_size()[1]
        widths = []
        for tab in tables:
            for i in range(0, len(tab.columns)):
                current_width = len(tab.columns[i].label)
                if len(widths) < i + 1:
                    widths.insert(i, current_width)
                elif widths[i] < current_width:
                    widths[i] = current_width
                for row in tab.data:
                    current_width = len(resolve_cell(row, tab.columns[i].accessor))
                    if current_width > widths[i]:
                        widths[i] = current_width

        if sum(widths) != terminal_size:
            widths[-1] = terminal_size - sum(widths[:-1]) - len(widths) * 3

        for tab in tables:
            table = Texttable(max_width=terminal_size)
            table.set_cols_width(widths)
            table.set_deco(0)
            table.header([i.label for i in tab.columns])
            table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
            six.print_(table.draw() + "\n")
开发者ID:jatinder-kumar-calsoft,项目名称:middleware,代码行数:25,代码来源:ascii.py


示例9: render_datasets_as_table

def render_datasets_as_table(datasets, display_heading=True):
    """
    Returns ASCII table view of datasets.

    :param datasets: The datasets to be rendered.
    :type datasets: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Dataset\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (datasets.url, datasets.total_count,
           datasets.limit, datasets.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm', 'm'])
    table.header(["Dataset ID", "Experiment(s)", "Description", "Instrument"])
    for dataset in datasets:
        table.add_row([dataset.id, "\n".join(dataset.experiments),
                       dataset.description, dataset.instrument])
    return heading + table.draw() + "\n"
开发者ID:wettenhj,项目名称:mytardisclient,代码行数:31,代码来源:views.py


示例10: draw

    def draw(self):
        t = Texttable()
        t.add_rows([["TEAM","RUNS","HITS","LOB","ERRORS"],
                    [self.away_team.team_name, self.away_runs, self.away_hits, self.away_LOB, self.away_errors],
                    [self.home_team.team_name, self.home_runs, self.home_hits, self.home_LOB, self.home_errors]])

        print(t.draw())
开发者ID:gdoe,项目名称:Baseball,代码行数:7,代码来源:scoreboard.py


示例11: display_two_columns

 def display_two_columns(cls, table_dict=None):
     if table_dict:
         ignore_fields = ['_cls', '_id', 'date_modified', 'date_created', 'password', 'confirm']
         table = Texttable(max_width=100)
         rows = [['Property', 'Value']]
         for key, value in table_dict.iteritems():
             if key not in ignore_fields:
                 items = [key.replace('_', ' ').title()]
                 if isinstance(value, list):
                     if value:
                         if key == "projects":
                             project_entry = ""
                             for itm in value:
                                 user_project = Project.objects(id=ObjectId(itm.get('$oid'))) \
                                     .only('title', 'project_id').first()
                                 project_entry = project_entry + user_project.title + ", "
                             project_entry.strip(', ')
                             items.append(project_entry)
                         else:
                             items.append(' , '.join(value))
                     else:
                         items.append('None')
                 else:
                     items.append(value)
                 rows.append(items)
         try:
             if rows:
                 table.add_rows(rows)
         except:
             print sys.exc_info()[0]
         print table.draw()
     pass
开发者ID:rajaramcomputers,项目名称:management,代码行数:32,代码来源:user.py


示例12: output_table

    def output_table(tab):
        max_width = get_terminal_size()[1]
        table = Texttable(max_width=max_width)
        table.set_deco(0)
        table.header([i.label for i in tab.columns])
        widths = []
        number_columns = len(tab.columns)
        remaining_space = max_width
        # set maximum column width based on the amount of terminal space minus the 3 pixel borders
        max_col_width = (remaining_space - number_columns * 3) / number_columns
        for i in range(0, number_columns):
            current_width = len(tab.columns[i].label)
            tab_cols_acc = tab.columns[i].accessor
            max_row_width = max(
                    [len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ]
                    )
            current_width = max_row_width if max_row_width > current_width else current_width
            if current_width < max_col_width:
                widths.insert(i, current_width)
                # reclaim space not used
                remaining_columns = number_columns - i - 1
                remaining_space = remaining_space - current_width - 3
                if remaining_columns != 0:
                    max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns
            else:
                widths.insert(i, max_col_width)
                remaining_space = remaining_space - max_col_width - 3
        table.set_cols_width(widths)

        table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
        print(table.draw())
开发者ID:williambr,项目名称:middleware,代码行数:31,代码来源:ascii.py


示例13: print_stats_table

def print_stats_table(
    header, data, columns, default_alignment="l", custom_alignment=None
):
    """Print out a list of dictionaries (or objects) as a table.

    If given a list of objects, will print out the contents of objects'
    `__dict__` attributes.

    :param header: Header that will be printed above table.
    :type header:  `str`
    :param data:   List of dictionaries (or objects )
    """
    print("# %s" % header)
    table = Texttable(max_width=115)
    table.header(columns)
    table.set_cols_align(default_alignment * len(columns))
    if not isinstance(data, list):
        data = [data]
    for row in data:
        # Treat all non-list/tuple objects like dicts to make life easier
        if not isinstance(row, (list, tuple, dict)):
            row = vars(row)
        if isinstance(row, dict):
            row = [row.get(key, "MISSING") for key in columns]
        table.add_row(row)
    if custom_alignment:
        table.set_cols_align(
            [custom_alignment.get(column, default_alignment) for column in columns]
        )
    print(table.draw())
开发者ID:Parsely,项目名称:streamparse,代码行数:30,代码来源:util.py


示例14: show_pretty_versions

def show_pretty_versions():
    result_list = list()
    header_list = ["IP", "Role", "Version", "Name", "Streamcast version", ]
    result_list.append(header_list)
    print("Versions installed:")
    ips = get_ips()
    for ip in ips:
        line = retrieve(sshcmd + ip + " cat /var/raumfeld-1.0/device-role.json")
        if "true" in line:
            moreinfo = "host"
        else:
            moreinfo = "slave"
        renderer_name = RfCmd.get_device_name_by_ip(ip)
        line = retrieve(sshcmd + ip + " cat /etc/raumfeld-version")
        line_streamcast = retrieve(sshcmd + ip + " streamcastd --version")
        single_result = list()
        single_result.append(ip)
        single_result.append(moreinfo)
        single_result.append(line.rstrip())
        single_result.append(renderer_name)
        single_result.append(line_streamcast.rstrip())
        result_list.append(single_result)
    t = Texttable(250)
    t.add_rows(result_list)
    print(t.draw())
开发者ID:scjurgen,项目名称:pyfeld,代码行数:25,代码来源:rfmacro.py


示例15: _create_app

def _create_app(args):
    api = _login(args)
    response = api.create_app(args.name, args.type, args.autostart, args.extra_info)
    print('App has been created:')
    table = Texttable(max_width=140)
    table.add_rows([['Param', 'Value']] + [[key, value] for key, value in response.items()])
    print(table.draw())
开发者ID:SuperCrunch,项目名称:django-webfaction,代码行数:7,代码来源:webfactionctl.py


示例16: test_texttable_header

def test_texttable_header():
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype([
        't',  # text
        'f',  # float (decimal)
        'e',  # float (exponent)
        'i',  # integer
        'a',  # automatic
    ])
    table.set_cols_align(["l", "r", "r", "r", "l"])
    table.add_rows([
        ["text",    "float", "exp", "int", "auto"],
        ["abcd",    "67",    654,   89,    128.001],
        ["efghijk", 67.5434, .654,  89.6,  12800000000000000000000.00023],
        ["lmn",     5e-78,   5e-78, 89.4,  .000000000000128],
        ["opqrstu", .023,    5e+78, 92.,   12800000000000000000000],
    ])
    assert clean(table.draw()) == dedent('''\
         text     float       exp      int     auto
        ==============================================
        abcd      67.000   6.540e+02    89   128.001
        efghijk   67.543   6.540e-01    90   1.280e+22
        lmn        0.000   5.000e-78    89   0.000
        opqrstu    0.023   5.000e+78    92   1.280e+22
    ''')
开发者ID:ah73,项目名称:pingSweep.py,代码行数:26,代码来源:tests.py


示例17: command_password

    def command_password(self, params):
        '''[set/get/list] <pdu> <port> <password>

        password set <pdu> <port> <password>
        Set port password on pdu
        e.g.
        - Set password "A01" for port 1 on pdu 1
        password set 1 1 A01

        password get <pdu> <port>
        Get port password on pdu
        e.g.
        - Get password for port 1 on pdu 1
        password get 1 1

        password list <pdu>
        Display password of all ports on pdu
        e.g.
        - Display all ports password on pdu 1
        password list 1

        '''
        subcommand = params[0]
        if subcommand == 'set':
            if len(params) != 4:
                self.writeresponse("Invalid parameters.")
                return
            pdu = int(params[1])
            port = int(params[2])
            passwd = params[3]
            password.write_password(pdu, port, passwd)
        elif subcommand == 'get':
            if len(params) != 3:
                self.writeresponse("Invalid parameters.")
                return
            pdu = int(params[1])
            port = int(params[2])
            password_str = password.read_password(pdu, port)
            if password_str == "":
                self.writeresponse("Not found password.")
                return
            response = "Password is: " + password_str
            self.writeresponse(response)
        elif subcommand == 'list':
            if len(params) != 2:
                self.writeresponse("Invalid parameters.")
                return

            pdu = int(params[1])
            table = Texttable()
            table.header(["Port", "Password"])
            table.set_cols_dtype(['d', 't'])
            table.set_cols_align(['c', 'c'])
            for port_index in range(24):
                passwd = password.read_password(pdu, port_index + 1)
                if passwd == "":
                    continue
                table.add_row([port_index + 1, passwd])
            self.writeresponse(table.draw())
开发者ID:InfraSIM,项目名称:vpduserv,代码行数:59,代码来源:infrasim-pduserv.py


示例18: _make_confusion_table

 def _make_confusion_table(self, labels, predictions):
     header = self._make_classes_header()
     C = confusion_matrix(labels, predictions)
     t = Texttable()
     t.add_row(['-'] + header)
     for i, h in enumerate(header):
         t.add_row([h] + C[i].tolist())
     return t
开发者ID:FilipStefaniuk,项目名称:MIMUW-DL-Project,代码行数:8,代码来源:simple_trainer.py


示例19: handle

 def handle(self):
     table = Texttable(max_width=0)
     table.set_deco(
         Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)
     table.header(("Processor", "Groups"))
     table.add_row(["Steps", ":".join(run.steps_groups())])
     table.add_row(["Alerts", ":".join(run.alerts_groups()) or "-"])
     print(table.draw())
开发者ID:toros-astro,项目名称:corral,代码行数:8,代码来源:commands.py


示例20: show_items

 def show_items(self, items):
     table = Texttable(max_width=0)
     table.header(['#', 'item'])
     table.set_deco(Texttable.HEADER | Texttable.VLINES)
     table.set_cols_dtype(['i', 't'])
     table.add_rows([(i, item) for i, item in enumerate(items)],
                    header=False)
     print(table.draw())
开发者ID:seanfisk,项目名称:selexec,代码行数:8,代码来源:views.py



注:本文中的texttable.Texttable类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python texture.Texture类代码示例发布时间:2022-05-27
下一篇:
Python textrect.render_textrect函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap