设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: manhong2112
打印 上一主题 下一主题

新人報到

[复制链接]

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

31#
发表于 2016-4-9 13:11:40 |显示全部楼层
本帖最后由 manhong2112 于 2016-12-8 21:44 编辑

之前寫的一堆排序算法...
  1. import random
  2. import timeit


  3. def printf(string, *obj):
  4.     return print(string.format(*obj))


  5. def bubble_sort(arr):
  6.     arr = arr[:]
  7.     for i in range(len(arr) - 1, 0, -1):
  8.         for j in range(i):
  9.             if arr[j] > arr[j + 1]:
  10.                 arr[j], arr[j + 1] = arr[j + 1], arr[j]
  11.     return arr


  12. def quick_sort(arr):
  13.     if len(arr) <= 1:
  14.         return arr
  15.     a = arr[0]
  16.     b = []
  17.     c = []
  18.     for i in arr[1:]:
  19.         (b if i < a else c).append(i)
  20.     return quick_sort(b) + [a] + quick_sort(c)


  21. def swap(arr, x, y):
  22.     arr[x], arr[y] = arr[y], arr[x]

  23. def quicksort_inplace_iter(arr):
  24.     stack = [(0, len(arr))]
  25.     while stack:
  26.         s, e = stack.pop()
  27.         s1, e1 = s, e
  28.         if s >= e:
  29.             continue
  30.         i = s
  31.         x = arr[e-1]
  32.         while s+1 < e1:
  33.             if arr[s] > x:
  34.                 swap(arr, s, e1 - 1)
  35.                 e1 -= 1
  36.             else:
  37.                 swap(arr, s, s1)
  38.                 s1 += 1
  39.             s += 1
  40.         stack.append((i, s))
  41.         stack.append((s+1, e))

  42. def random_arr(length):
  43.     arr = []
  44.     for i in range(length):
  45.         arr.append(random.randint(0, length ** 2))
  46.     return arr


  47. def merge_sort(arr):
  48.     def merge(arr1, arr2):
  49.         result = []
  50.         i = 0
  51.         j = 0
  52.         while True:
  53.             if i == len(arr1):
  54.                 result.extend(arr2[j:])
  55.                 break
  56.             if j == len(arr2):
  57.                 result.extend(arr1[i:])
  58.                 break
  59.             if arr1[i] < arr2[j]:
  60.                 result.append(arr1[i])
  61.                 i += 1
  62.             else:
  63.                 result.append(arr2[j])
  64.                 j += 1
  65.         return result

  66.     length = len(arr)
  67.     if length <= 1:
  68.         return arr
  69.     return arr if length <= 1 else merge(
  70.         merge_sort(arr[:int(length / 2)]),
  71.         merge_sort(arr[int(length / 2):]))


  72. def select_sort(arr):
  73.     for i in range(len(arr)):
  74.         for j in range(i, len(arr)):
  75.             if arr[j] < arr[i]:
  76.                 arr[i], arr[j] = arr[j], arr[i]
  77.     return arr


  78. def time(fun, *arr):
  79.     s = timeit.default_timer()
  80.     fun(*arr)
  81.     e = timeit.default_timer()
  82.     return((e - s) * 1000)
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

32#
发表于 2016-6-26 19:38:46 |显示全部楼层
筆記本
  1. import os
  2. import math
  3. import pickle
  4. sum = lambda x: 0 if len(x) == 0 else x[0] + sum(x[1:])


  5. class Reader(object):

  6.     def __init__(self, path=None):
  7.         self.Note = NoteManager.get_note(path)
  8.         self.Note.load()
  9.         pass

  10.     def read(self):
  11.         return self.Note.Context

  12.     def write(self, context):
  13.         self.Note.Context = context
  14.         pass

  15.     def write_line(self, context):
  16.         self.Note.Context += context
  17.         self.Note.Context += "\n"
  18.         pass

  19.     def append(self, context):
  20.         self.Note.Context += context
  21.         pass

  22.     def save(self):
  23.         with open(self.Note.nPath, "wb+") as f:
  24.             pickle.dump((self.Note.Context, self.Note.Type), f)


  25. class Note(object):
  26.     storageLoc = "./note"

  27.     def __init__(self, path, name, file_type="Text"):
  28.         assert type(name) is str
  29.         assert type(path) is str
  30.         assert type(file_type) is str
  31.         self.Name = name
  32.         self.Type = file_type
  33.         self.id = path
  34.         self.nPath = os.path.join(self.storageLoc, path)
  35.         self.Context = ""

  36.     def load(self):
  37.         os.makedirs(os.path.dirname(self.nPath), exist_ok=True)
  38.         if not os.path.isfile(self.nPath):
  39.             with open(self.nPath, "wb+") as f:
  40.                 pickle.dump(("", self.Type), f)
  41.         with open(self.nPath, "rb+") as f:
  42.             self.Context, self.Type = pickle.load(f)


  43. class NoteManager(object):
  44.     note_pool_loc = "./NoteList.db"
  45.     __note_pool = {}

  46.     @staticmethod
  47.     def get_note(path):
  48.         pool, name = NoteManager.parse_path(path)
  49.         return pool[name]["Note"]
  50.         pass

  51.     @staticmethod
  52.     def new_note(path, name, file_type="Text"):
  53.         n = Note(path, name, file_type)
  54.         NoteManager.add_note(path, n)
  55.         pass

  56.     @staticmethod
  57.     def filter(dir, f):
  58.         assert type(dir) is str
  59.         result = []
  60.         pool, name = NoteManager.parse_path(dir)
  61.         for i in pool:
  62.             if i[-1] == "/":
  63.                 result.extend(NoteManager.filter(dir + i, f))
  64.             elif (pool[i]["Tag"] & f) == f:
  65.                 result.append(dir + i)
  66.         return sorted(result)
  67.         pass

  68.     @staticmethod
  69.     def save():
  70.         tmp = {}

  71.         def _f(path, pool):
  72.             for p in pool:
  73.                 if p[-1] == "/":
  74.                     _f(path + p, pool[p])
  75.                 else:
  76.                     x = pool[p]
  77.                     tmp[p] = {"Tag": x["Tag"], "Name": x["Note"].Name}
  78.         _f("", NoteManager.__note_pool)
  79.         with open(NoteManager.note_pool_loc, "wb+") as f:
  80.             pickle.dump(tmp, f)
  81.         pass

  82.     @staticmethod
  83.     def add_note(path, note):
  84.         pool, name = NoteManager.parse_path(path)
  85.         pool[name] = {"Tag": 0, "Note": note}
  86.         pass

  87.     @staticmethod
  88.     def del_note(path):
  89.         os.remove(os.path.join(Note.storageLoc, path))
  90.         pool, name = NoteManager.parse_path(path)
  91.         pool.remove(name)
  92.         pass

  93.     @staticmethod
  94.     def add_tag(path, *tag):
  95.         pool, name = NoteManager.parse_path(path)
  96.         t = sum(tag)
  97.         if (pool[name]["Tag"] & t) != t:
  98.             pool[name]["Tag"] += t

  99.     @staticmethod
  100.     def del_tag(path, *tag):
  101.         pool, name = NoteManager.parse_path(path)
  102.         t = sum(tag)
  103.         if (pool[name]["Tag"] & t) == t:
  104.             pool[name]["Tag"] -= t

  105.     @staticmethod
  106.     def get_tag(path):
  107.         pool, name = NoteManager.parse_path(path)
  108.         t = pool[name]["Tag"]
  109.         tag = set({})
  110.         while t != 0:
  111.             x = int(math.log(t, 2))
  112.             t -= x
  113.             tag.add(TagManager.tag(x))
  114.             pass
  115.         return tag

  116.     @staticmethod
  117.     def parse_path(path):
  118.         x = path.split("/")
  119.         pool = NoteManager.__note_pool
  120.         for i in x[:-1]:
  121.             if i + "/" not in pool:
  122.                 pool[i + "/"] = {}
  123.             pool = pool[i + "/"]
  124.         return pool, x[-1]

  125.     if not os.path.isfile(note_pool_loc):
  126.         with open(note_pool_loc, "wb+") as f:
  127.             pickle.dump(__note_pool, f)
  128.     else:
  129.         with open(os.path.join(note_pool_loc), "rb+") as f:
  130.             tmp = pickle.load(f)
  131.         for i in tmp:
  132.             x = i.split("/")
  133.             pool = __note_pool
  134.             for i in x[:-1]:
  135.                 if i + "/" not in pool:
  136.                     pool[i + "/"] = {}
  137.                 pool = pool[i + "/"]
  138.             name = x[-1]
  139.             pool[name] = {"Tag": tmp[i]["Tag"],
  140.                           "Note": Note(i, tmp[i]["Name"])}


  141. class TagManager(object):
  142.     tag_pool_loc = "TagList.db"
  143.     __tag_pool = []

  144.     @staticmethod
  145.     def mk_filter(*tag):
  146.         return sum(tag)

  147.     @staticmethod
  148.     def new_tag(tag_name):
  149.         if tag_name not in TagManager.__tag_pool:
  150.             TagManager.__tag_pool.append(tag_name)
  151.         pass

  152.     @staticmethod
  153.     def tag(x):
  154.         if type(x) is str:
  155.             return 2**TagManager.__tag_pool.index(x)
  156.         elif type(x) is int:
  157.             return TagManager.__tag_pool[math.log(x, 2)]

  158.     @staticmethod
  159.     def save():
  160.         with open(os.path.join(TagManager.tag_pool_loc), "wb+") as f:
  161.             pickle.dump(TagManager.__tag_pool, f)
  162.         pass

  163.     if os.path.isfile(tag_pool_loc):
  164.         with open(os.path.join(tag_pool_loc), "rb+") as f:
  165.             __tag_pool = pickle.load(f)
  166.     else:
  167.         with open(os.path.join(tag_pool_loc), "wb+") as f:
  168.             pickle.dump(__tag_pool, f)

复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

33#
发表于 2016-8-15 20:25:00 |显示全部楼层
本帖最后由 manhong2112 于 2016-8-25 18:34 编辑

Brainfuck 解釋器(+半個編譯器)

  1. import msvcrt


  2. def interp(expr):
  3.     ptr = 0
  4.     ram = dict()
  5.     loopStack = []
  6.     excapingLoop = 0
  7.     i = 0
  8.     while(i < len(expr)):
  9.         # print(ram, loopStack, excapingLoop)
  10.         x = expr[i]
  11.         if not (ptr in ram) or ram[ptr] > 127 or ram[ptr] < -128:
  12.             ram[ptr] = 0
  13.         if x == "[":
  14.             if excapingLoop > 0:
  15.                 excapingLoop += 1
  16.             elif ram[ptr] != 0:
  17.                 loopStack.append(i)
  18.             else:
  19.                 excapingLoop = 1
  20.         elif x == "]":
  21.             if excapingLoop > 0:
  22.                 excapingLoop -= 1
  23.             elif ram[ptr] != 0:
  24.                 i = loopStack[-1]
  25.             else:
  26.                 loopStack.pop()
  27.         elif excapingLoop > 0:
  28.             pass
  29.         elif x == "+":
  30.             ram[ptr] += 1
  31.         elif x == "-":
  32.             ram[ptr] -= 1
  33.         elif x == ">":
  34.             ptr += 1
  35.         elif x == "<":
  36.             ptr -= 1
  37.         elif x == ".":
  38.             print(chr(ram[ptr]), end="")
  39.             pass
  40.         elif x == ",":
  41.             ram[ptr] = ord(msvcrt.getch())
  42.         i += 1

  43. version = 0x01
  44. header = [0x00, 0x10, 0x26, 0xBF, version, 0x00]
  45. # null, id, id, ver, id, mem_len


  46. class ID():
  47.     START_LOOP = 0
  48.     END_LOOP = 1
  49.     INC = 2
  50.     DEC = 3
  51.     NEXT = 4
  52.     BACK = 5
  53.     GETC = 6
  54.     PUTC = 7

  55.     ADD = 8
  56.     MOVE = 9


  57. def compile(expr):
  58.     result = header.copy()
  59.     state = 0
  60.     tmp = 0
  61.     memloc = 0
  62.     mmemloc = 0
  63.     loopStack = []
  64.     i = 0
  65.     while i <= len(expr):
  66.         # print(ram, loopStack, excapingLoop)
  67.         if memloc > mmemloc:
  68.             mmemloc = memloc
  69.         x = expr[i] if i != len(expr) else 0xFF
  70.         if state == 0:
  71.             if x == "[":
  72.                 loopStack.append(len(result))
  73.                 result.append(ID.START_LOOP)
  74.                 result.append(0)
  75.                 if memloc == 0:
  76.                     memloc = 1
  77.             elif x == "]":
  78.                 a = loopStack.pop()
  79.                 result[a + 1] = len(result) - a - 1
  80.                 result.append(ID.END_LOOP)
  81.                 result.append(len(result) - a + 1)
  82.             elif x == "+":
  83.                 state = ID.ADD
  84.                 tmp += 1
  85.             elif x == "-":
  86.                 state = ID.ADD
  87.                 tmp -= 1
  88.             elif x == ">":
  89.                 state = ID.MOVE
  90.                 tmp += 1
  91.             elif x == "<":
  92.                 state = ID.MOVE
  93.                 tmp -= 1
  94.             elif x == ".":
  95.                 result.append(ID.PUTC)
  96.             elif x == ",":
  97.                 result.append(ID.GETC)
  98.         elif state == ID.ADD:
  99.             if x in "+-":
  100.                 if x == "+":
  101.                     tmp += 1
  102.                 elif x == "-":
  103.                     tmp -= 1
  104.             else:
  105.                 if tmp == 0:
  106.                     pass
  107.                 elif tmp == 1:
  108.                     result.append(ID.INC)
  109.                 elif tmp == -1:
  110.                     result.append(ID.DEC)
  111.                 else:
  112.                     result.append(ID.ADD)
  113.                     result.append(tmp)
  114.                 state = 0
  115.                 i -= 1
  116.                 tmp = 0
  117.         elif state == ID.MOVE:
  118.             if x in "><":
  119.                 if x == ">":
  120.                     tmp += 1
  121.                 elif x == "<":
  122.                     tmp -= 1
  123.             else:
  124.                 if tmp == 0:
  125.                     pass
  126.                 elif tmp == 1:
  127.                     result.append(ID.NEXT)
  128.                     memloc += 1
  129.                 elif tmp == -1:
  130.                     result.append(ID.BACK)
  131.                     memloc -= 1
  132.                 else:
  133.                     result.append(ID.MOVE)
  134.                     result.append(tmp)
  135.                     memloc += tmp
  136.                 i -= 1
  137.                 state = 0
  138.                 tmp = 0
  139.         i += 1
  140.     result[5] = mmemloc
  141.     result.append(0xFF)
  142.     return result


  143. class Env(object):
  144.     def __init__(self, mem_len):
  145.         self.data = [0] * (mem_len + 1)
  146.         self.ptr = 0

  147.     def move(self, val):
  148.         self.ptr += val

  149.     def read(self):
  150.         return self.data[self.ptr]

  151.     def write(self, val):
  152.         self.data[self.ptr] = val if -128 <= val <= 127 else 0


  153. def execute(compiledExpr):
  154.     expr = compiledExpr
  155.     i = len(header)
  156.     env = Env(expr[5])
  157.     while i < len(expr) - 1:
  158.         x = expr[i]
  159.         if x == ID.INC:
  160.             env.write(env.read() + 1)
  161.         elif x == ID.DEC:
  162.             env.write(env.read() - 1)
  163.         elif x == ID.NEXT:
  164.             env.move(1)
  165.         elif x == ID.BACK:
  166.             env.move(-1)
  167.         elif x == ID.PUTC:
  168.             print(chr(env.read()), end="")
  169.         elif x == ID.GETC:
  170.             env.write(ord(msvcrt.getch()))
  171.         else:
  172.             if x == ID.START_LOOP and env.read() == 0:
  173.                 i += expr[i + 1]
  174.             elif x == ID.END_LOOP and env.read() != 0:
  175.                 i -= expr[i + 1]
  176.             elif x == ID.ADD:
  177.                 env.write(env.read() + expr[i + 1])
  178.             elif x == ID.MOVE:
  179.                 env.move(expr[i + 1])
  180.             i += 1
  181.         i += 1

  182. import timeit


  183. def time(fun, *arr):
  184.     s = timeit.default_timer()
  185.     fun(*arr)
  186.     e = timeit.default_timer()
  187.     return((e - s) * 1000)

  188. expr = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
  189. cexpr = compile(expr)

  190. x1, x2 = 0, 0
  191. for i in range(0, 100):
  192.     x1 += time(execute, cexpr)
  193. for i in range(0, 100):
  194.     x2 += time(interp, expr)

  195. print(x1 / 100)
  196. print(x2 / 100)
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

34#
发表于 2016-8-22 15:28:39 |显示全部楼层
本帖最后由 manhong2112 于 2016-8-22 16:00 编辑

寫了一個爬蟲, 一開始用lxml總是報錯(貌似是網站的HTML有問題)...就轉用BeautifulSoup了...
雖然能用, 但總感覺哪裡不太對勁..
EDIT: 相對路徑沒被簡化, 組成了一個迴圈....
EDIT: 找到了urljoin這函數, 希望不再出bug

  1. # from lxml import etree
  2. from bs4 import BeautifulSoup
  3. import urllib as request
  4. from urlparse import urljoin
  5. import re
  6. import os


  7. def getHtml(url):
  8.     res = request.urlopen(url)
  9.     try:
  10.         return url, res.read().decode("utf-8")
  11.     except Exception:
  12.         return url, res.read().decode("big5")


  13. def extractLink(url, html):
  14.     soup = BeautifulSoup(html, "html.parser")
  15.     return set(map(lambda i: re.sub("#.*$", "", urljoin(url, i["href"])), soup.findAll('a')))
  16.     # return set(etree.HTML(html).xpath("//a/@href"))


  17. target = "http://example.com/" # 目標網站
  18. startAt = "http://example.com/index.html" # 起始網頁
  19. output = "output" # 輸出
  20. downloadedLink = set()
  21. toBeDownload = set()
  22. toBeDownload.add(startAt)
  23. p = re.compile("https?://.*?/(.*)")

  24. while len(toBeDownload) != 0:
  25.     try:
  26.         url = toBeDownload.pop()
  27.         downloadedLink.add(url)
  28.         if (url.startswith("http") or url.startswith("https")) and not url.startswith(target):
  29.             continue
  30.         print "Downloading " + url
  31.         _, content = getHtml(url)
  32.         m = re.match(p, url)
  33.         m = m.group(1)
  34.         path, file = os.path.split(m)
  35.         try:
  36.             os.makedirs(os.path.join(output, path))
  37.         except Exception:
  38.             pass
  39.         with open(os.path.join(output, m), "w") as f:
  40.             f.write(content.encode('utf8'))
  41.         newUrl = extractLink(url, content).difference(downloadedLink)
  42.         toBeDownload = toBeDownload.union(newUrl)
  43.     except Exception:
  44.         print "Failed to Download " + url
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

35#
发表于 2016-10-10 21:00:38 |显示全部楼层
本帖最后由 manhong2112 于 2016-10-21 17:32 编辑

原本想弄個筆記本, 然後架個站自用...然後寫着寫着寫成了vcs(算嗎?算吧)......
話說混亂到自己都看不太下去了XDDD
EDIT: 換成if-else...感覺不想再看到python的lambda了....
EDIT: 大改了一下, 和把index的rollback功能刪了
  1. import hashlib
  2. import os
  3. import json
  4. import datetime
  5. import time

  6. dataLoc = "data"

  7. class Enitiy(object):

  8.     def __init__(self, name, dtype, hashcode, history):
  9.         self.name = name
  10.         self.dtype = dtype
  11.         self.hashcode = hashcode
  12.         self.history = history

  13. class Index(Enitiy):

  14.     def __init__(self, name, jsons=None, hashcode=None):
  15.         self.name = name
  16.         self.index = dict()
  17.         if jsons is not None:
  18.             for i in jsons["index"]:
  19.                 if i["type"] == "Index":
  20.                     self.index[i["name"]] = Index(
  21.                         i["name"],
  22.                         json.loads(read(i["hashcode"])),
  23.                         i["hashcode"])
  24.                 else:
  25.                     self.index[i["name"]] = Enitiy(
  26.                         i["name"],
  27.                         i["type"],
  28.                         i["hashcode"],
  29.                         i["history"] if "history" in i else dict())

  30.         super().__init__(name, "Index", hashcode, None)

  31.     def __str__(self):
  32.         return str(self.index)

  33.     def __getitem__(self, k):
  34.         return self.index[k]

  35.     def __setitem__(self, k, v):
  36.         self.index[k] = v

  37.     def __contains__(self, item):
  38.         return item in self.index

  39.     def __len__(self):
  40.         return len(self.index)

  41.     def items(self):
  42.         return self.index.items()

  43.     def dumpJsons(self):
  44.         result = dict()
  45.         result["index"] = []
  46.         result["name"] = self.name
  47.         for k, v in self.index.items():
  48.             obj = dict()
  49.             obj["name"], obj["type"], obj["hashcode"], obj["history"] = v.name, v.dtype, v.hashcode, v.history
  50.             result["index"].append(obj)
  51.         return json.dumps(result)

  52. _open = open
  53. def open(hashcode, type="w+"):
  54.     path = getPath(hashcode)
  55.     os.makedirs(os.path.dirname(path), exist_ok=True)
  56.     if os.path.isfile(path):
  57.         type = "r+"
  58.     else:
  59.         type = "w"
  60.     return _open(path, type, encoding="UTF-8")

  61. def getPath(hashcode):
  62.     return os.path.join(dataLoc, hashcode[:2], hashcode)

  63. def hash(str):
  64.     return hashlib.sha1(str).hexdigest()

  65. def hashStr(str):
  66.     return hash(str.encode("utf-8"))

  67. def hashFile(name, content):
  68.     return hash((name + "|" + content).encode("utf-8"))

  69. def read(hashcode):
  70.     with open(hashcode) as f:
  71.         return f.read()

  72. def init():
  73.     root = None
  74.     path = getPath("root")

  75.     name = "/"

  76.     if not os.path.isfile(path):
  77.         root = Index(name)
  78.         root_json = root.dumpJsons()
  79.         hashcode = hashFile(name, root_json)
  80.         with open(hashcode) as f:
  81.             f.write(root_json)
  82.         with open("root") as f:
  83.             f.write(json.dumps({"hashcode": hashcode, "name": name, "type": "Index"}))
  84.     else:
  85.         with open("root") as f:
  86.             accessPt = json.loads(f.read())
  87.             hashcode = accessPt["hashcode"]
  88.             with open(hashcode) as f:
  89.                 root = Index(name, json.loads(f.read()), hashcode)
  90.     return [root]

  91. def end(indexStack):
  92.     root = indexStack[0]
  93.     date = datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S")
  94.     name = "/"
  95.     content = root.dumpJsons()
  96.     hashcode = hashFile(name, content)
  97.     with open(hashcode) as f:
  98.         f.write(content)
  99.     with open("root") as f:
  100.         accessPt = json.loads(f.read())
  101.         f.seek(0)
  102.         accessPt["hashcode"] = hashcode
  103.         f.write(json.dumps(accessPt))
  104.         f.truncate()

  105. helpCmd = {
  106.     "update": ["Usage>> update <name> <type> <content>",
  107.                "Usage>> Update or create a file"],
  108.     "rollback": ["Usage>> rollback <name> <id>",
  109.                  "Usage>> Rollback to the specified id"],
  110.     "ls": ["Usage>> ls [name]",
  111.            "Usage>> list all file in current dir or specified dir"],
  112.     "cd": ["Usage>> cd <dir|'..'>",
  113.            "Usage>> cd to specified dir"],
  114.     "mkdir": ["Usage>> mkdir <dir>",
  115.               "Usage>> create a new dir at current dir"],
  116.     "read": ["Usage>> read <name>",
  117.              "Usage>> read the content of specified file"],
  118.     "history": ["Usage>> history <name>",
  119.                 "Usage>> List modifiy history of specified file"],
  120.     "help": ["Usage>> <cmd>", "Usage>> Print the usage of cmd",
  121.              "Usage>> all cmd[update, rollback, ls, cd, mkdir, read, history, help]"]
  122. }
  123. mainCmd = {"update", "rollback", "ls", "cd",
  124.            "mkdir", "read", "history", "help", }

  125. def update(indexStack, name, dtype, content):
  126.     index = indexStack[-1]
  127.     date = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
  128.     dateid = hashStr(date)[:6]
  129.     entity_hashcode = hashFile(name, content)

  130.     with open(entity_hashcode) as f:
  131.         f.write(content)

  132.     if name not in index:
  133.         if dtype == "Index":
  134.             index[name] = Index(name, hashcode=entity_hashcode)
  135.         else:
  136.             index[name] = Enitiy(name, dtype, entity_hashcode, dict())
  137.     else:
  138.         entity = index[name]
  139.         entity.history[dateid] = (date, entity.hashcode)
  140.         entity.hashcode = entity_hashcode

  141. def rollback(indexStack, name, datetimeid):
  142.     """
  143.     indexStack
  144.     name = file/dir name
  145.     datetimeid = date
  146.     """
  147.     index = indexStack[-1]
  148.     assert type(index[name]) is not Index
  149.     history = index[name].history
  150.     assert datetimeid in history
  151.     with open(history[datetimeid][1]) as f:
  152.         update(indexStack, name, index[name].dtype, f.read())

  153. def ls(indexStack, name=None):
  154.     if name is not None:
  155.         index = Index(name, json.loads(read(indexStack[-1][name].hashcode)))
  156.     else:
  157.         index = indexStack[-1]
  158.     assert type(index) is Index
  159.     return index.name, sorted([(e.name, e.dtype) for _, e in index.items()])
  160.    
  161. def cd(indexStack, name):
  162.     """
  163.     indexStack
  164.     name = file/dir name
  165.     """
  166.     assert type(indexStack) is list
  167.     assert type(name) is str
  168.     if name == "..":
  169.         indexStack.pop()
  170.     else:
  171.         index = indexStack[-1]
  172.         assert type(index[name]) is Index
  173.         indexStack.append(index[name])

  174. def getHistory(indexStack, name):
  175.     """
  176.     indexStack
  177.     name = file name
  178.     """
  179.     assert type(indexStack) is list
  180.     assert type(name) is str
  181.     index = indexStack[-1]
  182.     assert type(index[name]) is not Index
  183.     return index[name].history

  184. def mkdir(indexStack, name):
  185.     assert name not in indexStack[-1]
  186.     update(indexStack, name, "Index", Index(name).dumpJsons())

  187. if __name__ == '__main__':
  188.     indexStack = init()
  189.     try:
  190.         while True:
  191.             cmd = input("/".join([i.name for i in indexStack]) + ">> ").split(" ")
  192.             args = cmd[1:] if len(cmd) > 1 else []
  193.             if cmd[0] in mainCmd:
  194.                 if cmd[0] == "update":
  195.                     update(indexStack, *args)
  196.                 elif cmd[0] == "rollback":
  197.                     rollback(indexStack, args[0], args[1])
  198.                 elif cmd[0] == "ls":
  199.                     if len(args) == 1:
  200.                         i = ls(indexStack, *args)
  201.                     else:
  202.                         i = ls(indexStack)
  203.                     print(i[0] + " :"),
  204.                     print("\n".join(["\t" + n + " | " + t for n, t in i[1]]))
  205.                 elif cmd[0] == "cd":
  206.                     cd(indexStack, *args)
  207.                 elif cmd[0] == "mkdir":
  208.                     if len(args) != 1:
  209.                         print("E>")
  210.                     else:
  211.                         mkdir(indexStack, args[0])
  212.                 elif cmd[0] == "read":
  213.                     if len(args) != 1:
  214.                         print("E>")
  215.                     else:
  216.                         print(read(indexStack[-1][args[0]].hashcode)),
  217.                 elif cmd[0] == "history":
  218.                     if len(args) == 1:
  219.                         history = getHistory(indexStack, args[0])
  220.                         print(args[0] + " :")
  221.                         print("id\t|date")
  222.                         print("\n".join(
  223.                              ["{}\t|{}".format(x[0], x[1]) for x in
  224.                                sorted([(dateid, v[0]) for dateid, v in history.items()], key=lambda x: x[1])]))
  225.                     else:
  226.                         print("E>")
  227.                 elif cmd[0] == "help":
  228.                     exit = False
  229.                     while not exit:
  230.                         cmd = input("Help>> ")
  231.                         if cmd == "exit" or cmd == "quit":
  232.                             exit = True
  233.                         elif cmd in helpCmd:
  234.                             list(map(lambda x: print(x), helpCmd[cmd]))
  235.                         else:
  236.                             print("E> Invalid command")
  237.             elif cmd[0] == "exit" or cmd[0] == "quit":
  238.                 break
  239.             else:
  240.                 print("E> Invalid command")
  241.     except Exception:
  242.         raise
  243.     finally:
  244.         end(indexStack)
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

36#
发表于 2016-10-14 19:58:04 |显示全部楼层
和之前的筆記本一系列的, 用來抽取指定網址的內容!
目前只做了知乎, 以後再慢慢拓展
#註解掉的是md轉html的
  1. from bs4 import BeautifulSoup
  2. import urllib.request as urllib
  3. import re
  4. #import markdown


  5. def getContext(url):
  6.     data = parse(url, getRule(url))
  7.     md = """\
  8. {title}
  9. {author}
  10. {url}

  11. {content}\
  12. """.format(
  13.         title=("#" + data["title"]) if "title" in data else "",
  14.         author=("###" + data["author"]) if "author" in data else "",
  15.         url=("#####[Link](" + data["url"] + ")") if "url" in data else "",
  16.         content=("<hr><br>" + data["content"]) if "content" in data else "")
  17.     #return "<meta charset='UTF-8'>\n" + markdown.markdown(md, output_format="html5")
  18.     return md

  19. rule = [
  20.     (re.compile(r"https?://www.zhihu.com/question/\d*?/answer/\d*?#?.*"),
  21.      {"content": {"selector": "div#zh-question-answer-wrap .zm-editable-content"},
  22.       "title": {"selector": "div#zh-question-title > h2.zm-item-title > a"},
  23.       "author": {"selector": "span.author-link-line > a.author-link"},
  24.       "url": {"selector": "meta['http-equiv'='mobile-agent']", "attr": "content", "matching": re.compile(".*url=(.*)")}
  25.       })
  26. ]


  27. def getRule(url):
  28.     for k, v in rule:
  29.         if k.match(url):
  30.             return v


  31. def getHtml(url, encoding="utf-8"):
  32.     res = urllib.urlopen(url)
  33.     return res.read()


  34. def parse(url, rule):
  35.     result = dict()
  36.     soup = BeautifulSoup(getHtml(url), "html.parser")
  37.     for (k, v) in rule.items():
  38.         content = None
  39.         if "attr" in v:
  40.             content = str(soup.select(v["selector"])[0][v["attr"]]).strip(' \t\n\r')
  41.         else:
  42.             content = str(soup.select(v["selector"])[0].get_text()).strip(' \t\n\r')
  43.         if "matching" in v:
  44.             m = v["matching"].match(content)
  45.             if m:
  46.                 result[k] = m.group(1)
  47.         else:
  48.             result[k] = content
  49.     return result

  50. print(getContext("http://www.zhihu.com/question/51266789/answer/125952575"))
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-2 20:59 , Processed in 0.032054 second(s), 21 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部