blog

Source files for chris.bracken.jp
git clone https://git.bracken.jp/blog.git
Log | Files | Refs | Submodules | README | LICENSE

decay.py (1445B)


      1 #!/usr/bin/env python3
      2 
      3 import random
      4 import sys
      5 
      6 class Article:
      7   def __init__(self, text):
      8     self.text = text
      9     marker = "+++\n"
     10     header_start = text.find(marker)
     11     header_end = text.find(marker, header_start + len(marker)) + len(marker)
     12     self.header = self.text[:header_end]
     13     self.body = self.text[header_end:]
     14 
     15 
     16 def decay(text, maintain_fraction):
     17   """Returns the input string, intact by only maintain_fraction."""
     18   chars = list(text)
     19   length = len(chars)
     20   remove_count = int((1 - maintain_fraction) * length)
     21   for i in range(0, remove_count):
     22     pos = random.randrange(length)
     23     chars[pos] = "\u00a0"  # non-breaking space.
     24   return "".join(chars)
     25 
     26 
     27 def main():
     28   if len(sys.argv) < 2:
     29     sys.stderr.write("usage: decay.py FILE...")
     30     sys.exit(1)
     31 
     32   # For reproducibility, set random seet to the release date of Linda, Linda by
     33   # the Blue Hearts.
     34   random.seed(19870501)
     35 
     36   # Erode and rewrite each file.
     37   maintain_fraction = 0.98
     38   for filename in sys.argv[1:]:
     39     # Read the file.
     40     file = open(filename, "r")
     41     text = file.read()
     42     file.close()
     43 
     44     # Erode the text.
     45     article = Article(text)
     46     decayed_body = decay(article.body, maintain_fraction)
     47     decayed_contents = "".join([article.header, decayed_body])
     48 
     49     # Overwrite with the decayed contents.
     50     file = open(filename, "w")
     51     file.write(decayed_contents)
     52     file.close()
     53   return 0
     54 
     55 
     56 if __name__ == "__main__":
     57   sys.exit(main())