• 字符串替换


    题目: 给定一个英文的字符串, 要求你将其中的元音删除掉, 返回新的字符串.

    例如:
    "This website is for losers LOL!"  -->  "Ths wbst s fr lsrs LL!"

    当看到这个题目的时候, 第一个想起的就是re模块的正则表达式. 不过由于最近使用过字符串的replace方法, 所以我给出的解决方法是:

    def disemvowel(string):
        remove_list = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]    # 先列出元音列表
        for s in remove_list:
            while s in string:
                string = string.replace(s, "")  # 将元音字符替换为空再重新赋值回去
        return string

    这样就可以不用使用re模块就完成了要求. 但是, 还有人给出了更精妙的解决方案:

    def disemvowel(s):
        return s.translate(None, "aeiouAEIOU")

    还有许多其他的解决方案, 有兴趣的可以访问:

    https://www.codewars.com/kata/disemvowel-trolls/solutions/python/all/best_practice

    这里使用了一个字符串特别的方法, translate. 而这个方法平时我都没怎么注意过, 下面是官方文档的说明:

    S.translate(table [,deletechars]) -> string
    
    Return a copy of the string S, where all characters occurring
    in the optional argument deletechars are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256 or None.
    If the table argument is None, no translation is applied and
    the operation simply removes the characters in deletechars.


    返回一个字符串的副本, 所以出现在可选参数deletechars中的字符将会被移除, 而剩余的的字符将会通过给定的转化表进行映射替换, 这个表必须是长度256的字符串或者是None. 当为None时就不进行映射替换.

    所以 s.translate(None, "aeiouAEIOU") 的意思就是删除掉特定的字符了.

    而关于映射表的使用, 一般要借用string模块, 下面是一个示例:

    from string import maketrans
    
    in_str = "abc"
    out_str = "123"
    table = maketrans(in_str, out_str)
    raw_str = "abc def ghi"
    result = raw_str.translate(table, "ag")
    print result

    结果:

    按照方法的定义, 首先去除对应的字符, a和g在映射替换前其实已经被去掉了,  所以在进行映射替换的时候, a是不存在的, 所以并没有映射替换成1, 结果也就如上所示了.

    中文意义如何?

    #!/usr/bin/env python
    # coding: utf-8
    
    from string import maketrans
    
    in_str = ""
    out_str = ""
    table = maketrans(in_str, out_str)
    raw_str = "你好"
    result = raw_str.translate(table)
    print result

    结果:

    结论: 中文无意义, 不过一般来说, 做日志分析之类的工作时, 面对的多数是英文, 此时作用还是很大的.

  • 相关阅读:
    使用CSS3制图
    hdu4585 & BestCoder Round #1 项目管理(vector应用)
    ZooKeeperEclipse 小工具
    svn代码统计工具的金额
    【教你zencart仿站 文章1至6教训 高清1280x900视频下载】[支持手机端]
    [Django]models定义choices 字典中的页面显示值
    xml publisher根据条件显示或隐藏列
    hdu 1398 Square Coins(生成函数,完全背包)
    ubuntu软件中心崩溃
    PHP socket类
  • 原文地址:https://www.cnblogs.com/scolia/p/6116465.html
Copyright © 2020-2023  润新知