| 89 | #--- COMMONSENSE ----------------------------------------------------------------------------------- |
| 90 | |
| 91 | class Commonsense(Graph): |
| 92 | |
| 93 | def __init__(self, data=os.path.join(MODULE, "commonsense.csv"), **kwargs): |
| 94 | """ A semantic network of commonsense, using different relation types: |
| 95 | - is-a, |
| 96 | - is-part-of, |
| 97 | - is-opposite-of, |
| 98 | - is-property-of, |
| 99 | - is-related-to, |
| 100 | - is-same-as, |
| 101 | - is-effect-of. |
| 102 | """ |
| 103 | Graph.__init__(self, **kwargs) |
| 104 | self._properties = None |
| 105 | # Load data from the given path, |
| 106 | # a CSV-file of (concept1, relation, concept2, context, weight)-items. |
| 107 | if data is not None: |
| 108 | s = open(data).read() |
| 109 | s = s.strip(BOM_UTF8) |
| 110 | s = s.decode("utf-8") |
| 111 | s = ((v.strip("\"") for v in r.split(",")) for r in s.splitlines()) |
| 112 | for concept1, relation, concept2, context, weight in s: |
| 113 | self.add_edge(concept1, concept2, |
| 114 | type = relation, |
| 115 | context = context, |
| 116 | weight = min(int(weight)*0.1, 1.0)) |
| 117 | |
| 118 | @property |
| 119 | def concepts(self): |
| 120 | return self.nodes |
| 121 | |
| 122 | @property |
| 123 | def relations(self): |
| 124 | return self.edges |
| 125 | |
| 126 | @property |
| 127 | def properties(self): |
| 128 | """ Yields all concepts that are properties (i.e., adjectives). |
| 129 | For example: "cold is-property-of winter" => "cold". |
| 130 | """ |
| 131 | if self._properties is None: |
| 132 | #self._properties = set(e.node1.id for e in self.edges if e.type == "is-property-of") |
| 133 | self._properties = (e for e in self.edges if e.context == "properties") |
| 134 | self._properties = set(chain(*((e.node1.id, e.node2.id) for e in self._properties))) |
| 135 | return self._properties |
| 136 | |
| 137 | def add_node(self, id, *args, **kwargs): |
| 138 | """ Returns a Concept (Node subclass). |
| 139 | """ |
| 140 | self._properties = None |
| 141 | kwargs.setdefault("base", Concept) |
| 142 | return Graph.add_node(self, id, *args, **kwargs) |
| 143 | |
| 144 | def add_edge(self, id1, id2, *args, **kwargs): |
| 145 | """ Returns a Relation between two concepts (Edge subclass). |
| 146 | """ |
| 147 | self._properties = None |
| 148 | kwargs.setdefault("base", Relation) |
no outgoing calls
no test coverage detected
searching dependent graphs…