zoukankan      html  css  js  c++  java
  • Python如何使用不同分隔符切分字符串

    如何使用不同分割符分割字符串

    如何使用不同分隔符切分字符串,把某个字符串依据分隔符拆分,该字符包含不同的多种分隔符,如下

    s = '12;;7.osjd;.jshdjdknx+' 其中 ; . + 是分隔符

    有哪些解决方案?

    方法1:通过str.split()方法,每次处理一个分隔符

    #!/usr/bin/python3
    def go_split(s, symbol):
        result = [s]
        for i in symbol:
            median = []
            # 普通方法
            # for x in result:
            #     median.extend(x.split(i)
            # 列表解析
            # [median.extend(y.split(i)) for y in result if y]
            # map高阶函数,map生成可迭代对象
            for z in map(lambda x: x.split(i), result):
                median.extend(z)      
            # 以上三个方法都可以解决问题
            result = median   
        # 去除空字符串
        return [x for x in result if x]
    if __name__ == "__main__":
        # 定义初始字符串
        s = '12;;7.osjd;.jshdjdknx+'
        # 定义分隔符
        symbol = ';./+'
        result = go_split(s, symbol)
        print(result)

    方法2:通过re.split()方法,一次性拆分所有字符串,推荐

    #!/usr/bin/python3
    import re
    
    def go_split(s, symbol):
        # 拼接正则表达式
        symbol = "[" + symbol + "]+"
        # 一次性分割字符串
        result = re.split(symbol, s)
        # 去除空字符
        return [x for x in result if x]
    
    if __name__ == "__main__":
        # 定义初始字符串
        s = '12;;7.osjd;.jshdjdknx+'
        # 定义分隔符
        symbol = ';./+'
        result = go_split(s, symbol)
        print(result)

    一个文本转语音的小程序,对文本进行分割后,一句话一句话的读出来:

    # -*- coding: utf-8 -*-
    import pyttsx3
    import re
    import os
    engine = pyttsx3.init()
    # 分割原文
    def go_split(s, symbol):
        # 拼接正则表达式
        symbol = "[" + symbol + "]+"
        # 一次性分割字符串
        result = re.split(symbol, s)
        # 去除空字符
        return [x for x in result if x]
    # 判断字符串只包含中文:
    def reflag(list):
        for i in range(len(list)):
            for ch in list[i]:
                if ch >= 'u4e00' and ch <= 'u9fa5':
                    return i
    def reader(list,flag):
        if flag == None:
            print("本文没有中文翻译")
        else:
            print("本文有中文翻译")
        lenght = len(list)
        i = 0
        while i <lenght:
            instr = input("输入操作:"+"
    "
                          "1:继续听读本句话"+"
    "
                          "2:继续听读下一句话"+"
    "+":")
            if instr=="1":
                engine.say(list[i])
                print(list[i])
                engine.runAndWait()
            if instr == "2":
                i = i + 1
                print(list[i])
                engine.say(list[i])
                engine.runAndWait()
        print(list)
    def start():
        dirlsit= os.listdir('reader')
        for i in range(len(dirlsit)):
            print(str(i)+":"+str(dirlsit[i]))
        choice = int(input("输入选择的文章序号:"))
        with open("reader/"+dirlsit[choice],'r',encoding='utf-8') as f:
            article = f.read()
            article = article.replace('
    ', '')
            # 定义分隔符
            symbol = ',;.:'
            list = go_split(article,symbol)
            if filsh(list):
                flag = reflag(list) - 1
            else:flag=None
            rate = engine.getProperty('rate')
            engine.setProperty('rate', rate-25)
            reader(list,flag)
    
    start()

    文章格式:

    Night after night, she came to tuck me in, even long after my childhood years. Following her longstanding custom, she'd lean down and push my long hair out of the way, then kiss my forehead.
    I don't remember when it first started annoying me — her hands pushing my hair that way. But it did annoy me, for they felt work-worn and rough against my young skin. Finally, one night, I shouted out at her, "Don't do that anymore —your hands are too rough!" She didn't say anything in reply. But never again did my mother close out my day with that familiar expression of her love.
    Time after time, with the passing years, my thoughts returned to that night. By then I missed my mother's hands, missed her goodnight kiss on my forehead. Sometimes the incident seemed very close, sometimes far away. But always it lurked, in the back of my mind.
    Well, the years have passed, and I'm not a little girl anymore. Mom is in her mid-seventies, and those hands I once thought to be so rough are still doing things for me and my family. She's been our doctor, reaching into a medicine cabinet for the remedy to calm a young girl's stomach or soothe the boy's scraped knee. She cooks the best fried chicken in the world... gets stains out of blue jeans like I never could...
    Now, my own children are grown and gone. Mom no longer has Dad, and on special occasions, I find myself drawn next door to spend the night with her. So it was late on Thanksgiving Eve, as I slept in the bedroom of my youth, a familiar hand hesitantly run across my face to brush the hair from my forehead. Then a kiss, ever so gently, touched my brow.
    In my memory, for the thousandth time, I recalled the night my young voice complained, "Don't do that anymore — your hands are too rough!" Catching Mom's hand in hand, I blurted out how sorry I was for that night. I thought she'd remember, as I did. But Mom didn't know what I was talking about. She had forgotten — and forgiven — long ago.
    That night, I fell asleep with a new appreciation for my gentle mother and her caring hands. And the guilt that I had carried around for so long was nowhere to be found.
    【中文译文】:
    母亲总是在我入睡之后,为我掖好被子,然后俯下身子,轻轻拨开覆在我脸上的长发,亲吻我的前额。日复一日,母亲一直保持着这个习惯,即使我已不再是小孩子了,这一切却依然故我。
    不知从什么时候开始,母亲的这种习惯渐渐让我感到不悦----我不喜欢她那双布满老茧的手就这样划过我细嫩的皮肤。终于,在一个夜晚,我忍不住冲她吼了起来:“你不要再这样了,你的手好粗糙!”母亲无言以对。但从此却再没有用这种我熟悉的表达爱的方式来为我的一天画上句号。
    日子一天天过去,随着时间的流逝,我却总是不由得想起那一夜。我开始想念母亲的那双手,想念她印在我前额上的“晚安”。这种渴望忽远忽近,但始终潜藏在我心灵深处的某个角落。
    若干年后,我成熟了,已不再是个小女孩了。母亲也已到了古稀之年,可她却始终没有停止过操劳,用她那双曾经被我视为“粗糙”的手为我和我的家庭做着力所能及的事情。她是我们的家庭医生,小姑娘胃痛时,她会从药箱里找出胃药来,小男孩擦伤的膝盖时,她会去安抚他的伤痛。她能做出世界上最好吃的炸鸡,能把蓝色牛仔裤上的污渍去得毫无痕迹......
    现在,我自己的孩子也已长大,有了自己的生活,母亲却没有了父亲的陪伴。有一次,恰好是感恩节前夜,我决定就睡在母亲旁边的卧室里,陪她度过这一夜。这是我儿时的卧室,一切都是那么的熟悉,还有一只熟悉的手犹豫着从我的脸上掠过,梳理着我前额的头发,然后,一个吻,带着一如往日的温柔,轻轻落在了我的额头。
    在我的记忆里,曾几千次再现那晚的情景和我那稚嫩的抱怨声:“你不要再这样了,你的手好粗糙!”我一把抓住母亲的手,一股脑说出我对那一晚深深的愧疚。我想,她一定和我一样,对那晚的事历历在目。然而,母亲却不知我再说些什么-----她早忘了,早已原谅我了。
    那天晚上,我带着对母亲新的感激安然入睡,我感激她的温柔,和她那呵护的双手。多年来压在我心头的负罪感也随之烟消云散。
    

     

  • 相关阅读:
    Raw图像格式
    Basler相机外部触发设置(Halcon)
    C# 丢弃串口缓冲区 Serialport.DiscardInBuffer,DiscardOutBuffer
    ASCII 码
    Xcopy 使用详解
    Qt 信息提示框QMessageBox用法
    Qt 调整图片大小适应QLabel
    C++取整
    Qt QTableView数据列宽度自适应, 横向填满表格
    Qt 事件总结(鼠标、键盘) QMouseEvent、QKeyEvent
  • 原文地址:https://www.cnblogs.com/-wenli/p/12594409.html
Copyright © 2011-2022 走看看