当前位置: 首页>>代码示例>>Python>>正文


Python texttable.Texttable类代码示例

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


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


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