Create (sane/safe) filename from any (unsafe) string

前端 未结 11 1328
醉酒成梦
醉酒成梦 2020-12-28 12:45

I want to create a sane/safe filename (i.e. somewhat readable, no \"strange\" characters, etc.) from some random Unicode string (mich might contain just anything).

(

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 13:20

    Here is what I came with, being inspired by uglycoyote:

    import time
    
    def make_safe_filename(s):
        def safe_char(c):
            if c.isalnum() or c=='.':
                return c
            else:
                return "_"
    
        safe = ""
        last_safe=False
        for c in s:
          if len(safe) > 200:
            return safe + "_" + str(time.time_ns() // 1000000)
    
          safe_c = safe_char(c)
          curr_safe = c != safe_c
          if not last_safe or not curr_safe:
            safe += safe_c
          last_safe=curr_safe
        return safe
    

    And to test:

    print(make_safe_filename( "hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!hello you crazy $#^#& 2579 people!!! : hi!!!" ) + ".gif")
    

提交回复
热议问题