various methods to parse pages from thingiverse
[skdb.git] / dice.py
blob16d283d77cae8604747962ad8fde812286ab787d
1 '''example code for yaml magic from pyyaml.org documentation.
2 see http://pyyaml.org/wiki/PyYAMLDocumentation#Constructorsrepresentersresolvers'''
4 import yaml, re
5 #def dice_constructor(Dice, data):
6 #major, minor =[int(x) for x in data.split('d')]
7 #return Dice(major, minor)
9 class Dice(yaml.YAMLObject):
10 yaml_tag = '!dice'
11 yaml_pattern = re.compile('^\d+d\d+$')
12 def __init__(self, major, minor):
13 self.major = major
14 self.minor = minor
15 def __repr__(self):
16 return "Dice(%s,%s)" % (self.major, self.minor)
17 def yaml_repr(self):
18 return "%sd%s" % (self.major, self.minor)
19 @classmethod
20 def to_yaml(cls, dumper, data):
21 return dumper.represent_scalar(cls.yaml_tag, cls.yaml_repr(data)) #not sure this is right
22 @classmethod
23 def from_yaml(cls, loader, node):
24 data = loader.construct_scalar(node)
25 major, minor = [int(x) for x in data.split('d')]
26 return cls(major, minor)
28 class Foo(yaml.YAMLObject):
29 yaml_tag = '!foo'
30 yaml_pattern = re.compile('foo(.*)')
31 def __init__(self, value):
32 self.value = value
33 def __repr__(self):
34 return "Foo(%s)" %(self.value)
35 def yaml_repr(self):
36 return "foo%s" % self.value
37 @classmethod
38 def to_yaml(cls, dumper, data):
39 return dumper.represent_scalar(cls.yaml_tag, cls.yaml_repr(data)) #not sure this is right
40 @classmethod
41 def from_yaml(cls, loader, node):
42 match = re.search(cls.yaml_pattern, loader.construct_scalar(node))
43 if match:
44 return Foo(match.group(1))
45 else:
46 return Foo(loader.construct_scalar(node))
48 class FirstResolver(yaml.YAMLObject):
49 yaml_tag="!first"
50 some_attr="foobars"
51 def __init__(self, extra):
52 if extra: some_attr=extra
53 @classmethod
54 def from_yaml(cls, loader, node):
55 data = loader.construct_scalar(node)
56 return cls(data)
58 class SecondResolver(FirstResolver):
59 yaml_tag="!second"
60 some_attr="barfoo"
62 #teach PyYAML that any untagged scalar with the path [a] has an implict tag !first
63 yaml.add_path_resolver("!first", ["a"], str)
65 #teach PyYAML that any untagged scalar with the path [a,b,c] has an implicit tag !second.
66 yaml.add_path_resolver("!second", ["a", "b", "c"], str)
68 #teach PyYAML that any untagged plain scalar that looks like XdY has the implicit tag !dice.
69 for cls in [Dice, Foo]:
70 yaml.add_implicit_resolver(cls.yaml_tag, cls.yaml_pattern)
72 def load(foo):
73 return yaml.load(foo)
75 def dump(foo):
76 return yaml.dump(foo, default_flow_style=False)
78 print "loading '2d6' turns into: ", load('2d6')
79 print "dumping Dice(2,6) looks like: ", dump(Dice(2,6))
80 print "loading foomoo: ", load('foomoo')
81 print "loading !foo bar: ", load('!foo bar')
82 print "dumping Foo(moo): ", dump(Foo("moo"))
83 print "loading a: moo ", load("a: moo")
84 print "loading a: b: c: input goes here", load("a:\n b:\n c: input goes here")