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


Python TextWrapper.width方法代码示例

本文整理汇总了Python中textwrap.TextWrapper.width方法的典型用法代码示例。如果您正苦于以下问题:Python TextWrapper.width方法的具体用法?Python TextWrapper.width怎么用?Python TextWrapper.width使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在textwrap.TextWrapper的用法示例。


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

示例1: test_fix_sentence_endings

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
    def test_fix_sentence_endings(self):
        wrapper = TextWrapper(60, fix_sentence_endings=True)

        # SF #847346: ensure that fix_sentence_endings=True does the
        # right thing even on input short enough that it doesn't need to
        # be wrapped.
        text = "A short line. Note the single space."
        expect = ["A short line.  Note the single space."]
        self.check(wrapper.wrap(text), expect)

        # Test some of the hairy end cases that _fix_sentence_endings()
        # is supposed to handle (the easy stuff is tested in
        # test_whitespace() above).
        text = "Well, Doctor? What do you think?"
        expect = ["Well, Doctor?  What do you think?"]
        self.check(wrapper.wrap(text), expect)

        text = "Well, Doctor?\nWhat do you think?"
        self.check(wrapper.wrap(text), expect)

        text = 'I say, chaps! Anyone for "tennis?"\nHmmph!'
        expect = ['I say, chaps!  Anyone for "tennis?"  Hmmph!']
        self.check(wrapper.wrap(text), expect)

        wrapper.width = 20
        expect = ["I say, chaps!", 'Anyone for "tennis?"', "Hmmph!"]
        self.check(wrapper.wrap(text), expect)

        text = 'And she said, "Go to hell!"\nCan you believe that?'
        expect = ['And she said, "Go to', 'hell!"  Can you', "believe that?"]
        self.check(wrapper.wrap(text), expect)

        wrapper.width = 60
        expect = ['And she said, "Go to hell!"  Can you believe that?']
        self.check(wrapper.wrap(text), expect)
开发者ID:Jarga,项目名称:IBM-Innovate-2012,代码行数:37,代码来源:test_textwrap.py

示例2: _stream_formatter

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
    def _stream_formatter(self, record):
        """The formatter for standard output."""
        if record.levelno < logging.DEBUG:
            print(record.levelname, end='')
        elif(record.levelno < logging.INFO):
            colourPrint(record.levelname, 'green', end='')
        elif(record.levelno < IMPORTANT):
            colourPrint(record.levelname, 'magenta', end='')
        elif(record.levelno < logging.WARNING):
            colourPrint(record.levelname, 'lightblue', end='')
        elif(record.levelno < logging.ERROR):
            colourPrint(record.levelname, 'brown', end='')
        else:
            colourPrint(record.levelname, 'red', end='')

        if record.levelno == logging.WARN:
            message = '{0}'.format(record.msg[record.msg.find(':')+2:])
        else:
            message = '{0}'.format(record.msg)

        if len(message) > self.wrapperLength:
            tw = TextWrapper()
            tw.width = self.wrapperLength
            tw.subsequent_indent = ' ' * (len(record.levelname)+2)
            tw.break_on_hyphens = False
            message = '\n'.join(tw.wrap(message))

        print(': ' + message)
开发者ID:ApachePointObservatory,项目名称:Totoro,代码行数:30,代码来源:logger.py

示例3: list_posts

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def list_posts(discussions):
        t = PrettyTable([
            "identifier",
            "title",
            "category",
            "replies",
            # "votes",
            "payouts",
        ])
        t.align = "l"
        t.align["payouts"] = "r"
        # t.align["votes"] = "r"
        t.align["replies"] = "c"
        for d in discussions:
            identifier = "@%s/%s" % (d["author"], d["permlink"])
            identifier_wrapper = TextWrapper()
            identifier_wrapper.width = 60
            identifier_wrapper.subsequent_indent = " "

            t.add_row([
                identifier_wrapper.fill(identifier),
                identifier_wrapper.fill(d["title"]),
                d["category"],
                d["children"],
                # d["net_rshares"],
                d["pending_payout_value"],
            ])
        print(t)
开发者ID:PixelNoob,项目名称:piston,代码行数:30,代码来源:ui.py

示例4: dump_recursive_comments

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def dump_recursive_comments(rpc,
                            post_author,
                            post_permlink,
                            depth=0,
                            format="markdown"):
    global currentThreadDepth
    postWrapper = TextWrapper()
    postWrapper.width = 120
    postWrapper.initial_indent = "  " * (depth + currentThreadDepth)
    postWrapper.subsequent_indent = "  " * (depth + currentThreadDepth)

    depth = int(depth)

    posts = rpc.get_content_replies(post_author, post_permlink)
    for post in posts:
        meta = {}
        for key in ["author", "permlink"]:
            meta[key] = post[key]
        meta["reply"] = "@{author}/{permlink}".format(**post)
        if format == "markdown":
            body = markdownify(post["body"])
        else:
            body = post["body"]
        yaml = frontmatter.Post(body, **meta)
        print(frontmatter.dumps(yaml))
        reply = rpc.get_content_replies(post["author"], post["permlink"])
        if len(reply):
            dump_recursive_comments(rpc, post["author"], post["permlink"], depth + 1)
开发者ID:PixelNoob,项目名称:piston,代码行数:30,代码来源:ui.py

示例5: wrap_for_make

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def wrap_for_make(items):
    line = join(sorted(items))
    wrapper = TextWrapper()
    wrapper.width = 60
    wrapper.break_on_hyphens = False
    wrapper.subsequent_indent = '\t' * 2
    return ' \\\n'.join(wrapper.wrap(line))
开发者ID:handsomegui,项目名称:mpd-win32-build,代码行数:9,代码来源:buildtool.py

示例6: dump_recursive_parents

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def dump_recursive_parents(rpc,
                           post_author,
                           post_permlink,
                           limit=1,
                           format="markdown"):
    global currentThreadDepth

    limit = int(limit)

    postWrapper = TextWrapper()
    postWrapper.width = 120
    postWrapper.initial_indent = "  " * (limit)
    postWrapper.subsequent_indent = "  " * (limit)

    if limit > currentThreadDepth:
        currentThreadDepth = limit + 1

    post = rpc.get_content(post_author, post_permlink)

    if limit and post["parent_author"]:
        parent = rpc.get_content_replies(post["parent_author"], post["parent_permlink"])
        if len(parent):
            dump_recursive_parents(rpc, post["parent_author"], post["parent_permlink"], limit - 1)

    meta = {}
    for key in ["author", "permlink"]:
        meta[key] = post[key]
    meta["reply"] = "@{author}/{permlink}".format(**post)
    if format == "markdown":
        body = markdownify(post["body"])
    else:
        body = post["body"]
    yaml = frontmatter.Post(body, **meta)
    print(frontmatter.dumps(yaml))
开发者ID:PixelNoob,项目名称:piston,代码行数:36,代码来源:ui.py

示例7: printHeader

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def printHeader(s, level=1, length=70, prefix='# <Menotexport>:'):
    from textwrap import TextWrapper

    decs={1: '=', 2: '-', 3: '.'}
    indents={1: 0, 2: 4, 3: 8}

    dec=decs[level]
    ind=indents[level]
    indstr=' '*int(ind)

    wrapper=TextWrapper()
    wrapper.width=length-ind
    wrapper.initial_indent=indstr
    wrapper.subsequent_indent=indstr

    #-------------Get delimiter line-------------
    hline='%s%s' %(' '*int(ind),dec*int(length-ind)) 

    #--------------------Wrap texts--------------------
    strings=wrapper.wrap('%s %s' %(prefix,s))

    #----------------------Print----------------------
    try:
        print('\n'+hline)
    except:
        print('\n'+hline.encode('ascii','replace'))
    for ss in strings:
        try:
            print(ss)
        except:
            print(ss.encode('ascii','replace'))
    #print(hline)

    return
开发者ID:Xunius,项目名称:Menotexport,代码行数:36,代码来源:tools.py

示例8: default_attribute_formatter

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
 def default_attribute_formatter(self, key, value):
   wrapper = TextWrapper()
   wrapper.initial_indent='FT                   '
   wrapper.subsequent_indent='FT                   '
   wrapper.width=79
   attribute_text_template='/{attribute_key}="{attribute_value}"'
   attribute_text=attribute_text_template.format(attribute_key=key, attribute_value=value)
   return wrapper.fill(attribute_text)
开发者ID:JTumelty,项目名称:gff3toembl,代码行数:10,代码来源:EMBLContig.py

示例9: __init__

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
	def __init__(self, width=80):
		""" Sets up the class and configures the utilized Textwrapper-object"""
		self.width = width
		wrapper = TextWrapper()
		wrapper.width = width	
		wrapper.replace_whitespace = False	
		wrapper.drop_whitespace = False	
		self.wrapper = wrapper
开发者ID:jmtoball,项目名称:StudICLI,代码行数:10,代码来源:asciioutput.py

示例10: number_attribute_formatter

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
 def number_attribute_formatter(self, key, value):
   # transl_table attributes do not have their values in quotes
   wrapper = TextWrapper()
   wrapper.initial_indent='FT                   '
   wrapper.subsequent_indent='FT                   '
   wrapper.width=79
   attribute_text_template='/{attribute_key}={attribute_value}'
   attribute_text=attribute_text_template.format(attribute_key=key, attribute_value=value)
   return wrapper.fill(attribute_text)
开发者ID:JTumelty,项目名称:gff3toembl,代码行数:11,代码来源:EMBLContig.py

示例11: header_attribute_formatter

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
 def header_attribute_formatter(self, key, header_text, quote_character, final_character):
   wrapper = TextWrapper()
   wrapper.initial_indent=key + '   '
   wrapper.subsequent_indent=key + '   '
   wrapper.width=79
   attribute_text_template='{attribute_quote_character}{attribute_header_text}{attribute_quote_character}{attribute_final_character}'
   attribute_text=attribute_text_template.format(attribute_header_text = header_text, 
                                                 attribute_quote_character = quote_character, 
                                                 attribute_final_character = final_character)
   return wrapper.fill(attribute_text)
开发者ID:JTumelty,项目名称:gff3toembl,代码行数:12,代码来源:EMBLContig.py

示例12: product_attribute_formatter

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
 def product_attribute_formatter(self, key, value):
   # Products can include very long enzyme names which we don't want to break
   wrapper = TextWrapper()
   wrapper.initial_indent='FT                   '
   wrapper.subsequent_indent='FT                   '
   wrapper.width=79
   wrapper.break_on_hyphens=True
   attribute_text_template='/{attribute_key}="{attribute_value}"'
   attribute_text=attribute_text_template.format(attribute_key=key, attribute_value=value)
   return wrapper.fill(attribute_text)
开发者ID:JTumelty,项目名称:gff3toembl,代码行数:12,代码来源:EMBLContig.py

示例13: linewrap

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def linewrap(width = None):
    """Returns a function that wraps long lines to a max of 251 characters.
	Note that this function returns a list of lines, which is suitable as the
	argument for the spss.Submit function.
    """
    wrapper = TextWrapper()
    wrapper.width = width or 251
    wrapper.replace_whitespace = True
    wrapper.break_long_words = False
    wrapper.break_on_hyphens = False
    return wrapper.wrap
开发者ID:matt-hayden,项目名称:python-utilities,代码行数:13,代码来源:spss_functions.py

示例14: main

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def main():
    """Parse command line options
    
    """
    
    usage = "usage: %(prog)s [options]"
    parser = ArgumentParser(prog='pydylogger', usage=usage,
                            )#formatter_class=RawTextHelpFormatter)
    
    tw = TextWrapper()
    mywrap = lambda x: "\n".join(tw.wrap(x))
    tw.width = 80 - 25
    
    #
    parser.add_argument('arglist', nargs='*', default=list(), help='N/A')
    parser.add_argument('-t', '--translate', action="store_true", \
            dest="translate", default=False, help="Print human readable " \
            "packets. Default: %(default)s")
    parser.add_argument('-a', '--all', action="store_true", \
            dest="saveall", default=False, help="Optionally save all bytes/" \
            "packets, including malformed packets. Default: %(default)s")
    parser.add_argument('-o', '--output', action="store", \
            dest="output", default="logging_output.txt", help="Specify output " \
            "file for log of packets. Default: %(default)s")
    #
    
    options = parser.parse_args()
    args = options.arglist
    
    # TODO get rid of these globals...
    global saveall
    global translate
    saveall = options.saveall
    translate = options.translate
    
    global port
    global baud
    global timing
    global id_dict
    cfg = PyDyConfigParser()
    cfg.read()
    port, baud, __, timing, __ = cfg.get_params()
    id_dict = cfg.get_id_to_device_dict()

    if saveall:
        print "All packets (including bad packets) will be saved in " \
                "{0}".format(options.output)
    if translate:
        print "Packets will be translated for listing in this window."
    
    logger_method(outputfile=options.output)
    
    return
开发者ID:erelson,项目名称:PyDyPackets,代码行数:55,代码来源:pydylogger.py

示例15: draw_body

# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import width [as 别名]
def draw_body(card, raw_text, center_y, card_width, chars_per_line):
	text = raw_text.decode('utf-8')
	wrapper = TextWrapper()
	wrapper.width = chars_per_line
	wrapper.replace_whitespace = True
	wrapper.drop_whitespace = False
	lines = wrapper.wrap(text)
	line_width, line_height = body_font.getsize(lines[0])
	y = center_y - (line_height * (float(len(lines)) / 2.0))
	for line in lines:
		line_width, line_height = body_font.getsize(line)
		draw = ImageDraw.Draw(card)
		draw.text(((card_width - line_width) / 2, y), line, font = body_font, fill = (0, 0, 0))
		y += line_height
开发者ID:eriksvedang,项目名称:card-creator,代码行数:16,代码来源:card.py


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