文本处理-python

作者: _String_ | 来源:发表于2017-05-24 15:46 被阅读0次

    string--文本常量和模板

    string模块最常用的两个函数是capwords()和maketrans(),capwords()是将所有单词首字母大写。
    用法如下:

    str = 'the quick brown fox jumped over'
    print string.capwords(str)
    输出结果为:The Quick Brown Fox Jumped Over
    maketrans()函数将创建转换标表,可以来结合translate()方法将一组字符修改为另一种字符。
    maketrans使用示例如下:
    import string
    leet = string.maketrans('abegiloprstz','463611092572')
    s = 'the quick bronw fox jumped over the lazy dog.'
    print s.translate(leet)

    image.png

    模板

    使用string.Template拼接时可以在变量名前面加上前缀¥如¥var来标识变量,如果为区分两侧字符还科以通过大括号区分如${var}.

    value ={'var':'foo'}
    t = string.Template("""
    Variable :$var
    Escape :$$
    Variable in test:${var}iable
    """)

    image.png

    示例代码如下:

    #!/usr/bin/env python
    import string
    
    values = {'var':'foo'}
    t = string.Template("$var is here but $missing is not provided")
    
    try:
        print 'substitute()     :',t.substitute(values)
    except KeyError, err:
        print 'ERROR:', str(err)
    
    print 'safe_substitute():',t.safe_substitute(values)
    
    image.png

    高级模板

    可以修改string.Template的默认语法,修改delimiter和idpattern调整在模板中查找变量名所使用的正则表达式。
    使用方法如下:

    定义一个字符串

    template_text ='''
         Delimiter:%%
         Replaced :%with_underscore
         Ignored  :%notunderscored
     '''
    

    定义字典内容
    d ={'with_underscore':'replaced', 'notunderscored':'not replaced',}
    实例化模板对象

    class MyTemplate(string.Template):
    ...     delimiter = '%'    #定义变量前缀
    ...     idpattern = '[a-z]+_[a-z]+'   #定义变量查找规则
    

    调用结果如图:

    image.png

    同托修改pattern属性,可以定义正则表达式完成更负杂的变量规则
    可以通过pattern属性访问模板对象的变量查找规则如下:

    t = string.Template($var)
    print t.pattern.pattern

    \$(?:
          (?P<escaped>\$) |   # Escape sequence of two delimiters
          (?P<named>[_a-z][_a-z0-9]*)      |   # delimiter and a Python identifier
          {(?P<braced>[_a-z][_a-z0-9]*)}   |   # delimiter and a braced identifier
          (?P<invalid>)              # Other ill-formed delimiter exprs
        )
    

    通过修改pattern属性值修改变量查找规则示例如下:

    textwrap——格式化文本段落

    引入textwrap后可通过各函数控制文本格式操作示例如下。

    保存模板文件textwrap——example.py

    sample_text ='''The protein window is divided in two part: left and right. The right part is displayed only when we have the protein structure (or a model of the protein structure) stored in our database. Note that for each new release of STRING we store in the images of crystallized protein (from PDB) as well as the images of protein models (from SwissModel). Since both PDB and SwissModel are updated more frequently than STRING, we suggest to directly look for structures/models on the PDB and SwissModel websites.'''
    

    新建测试文件内容如下:

    #!/usr/bin/env pytnon
    import textwrap
    from textwrap_example import sample_text
    print 'NO dedent:\n'
    print textwrap.fill(sample_text,width=50)
    print '='*30
    dedented_text = textwrap.dedent(sample_text)
    print dedented_text
    

    通过dedent()函数去除缩进,indent()增加缩进。
    通过dedent去除缩进后通过full控制输出宽度如下:

    \#!/usr/bin/env pytnon
    import textwrap
    from textwrap_example import sample_text
    print 'NO dedent:\n'
    print textwrap.fill(sample_text,width=50)
    print '='*30
    dedented_text = textwrap.dedent(sample_text)
    print dedented_text
    print '='*30
    dedented_text2 = textwrap.dedent(sample_text).strip()
    for width in [45,70]:
        print '%d columns:\n' % width
        print textwrap.fill(dedented_text2,width=width)
        print
    

    textwrap除了支持控制文本长度和删除缩进还支持其他格式,如悬挂缩进等。

    悬挂缩进

    通过控制full函数subsequent和initial_indent的属性设置可实现悬挂缩进示例代码如下:

    print textwrap.fill(dedented_text,
                        initial_indent='',
                        subsequent_indent=' '*4,
                        width=50,
                        )
    
    image.png

    相关文章

      网友评论

        本文标题:文本处理-python

        本文链接:https://www.haomeiwen.com/subject/txqwxxtx.html