2009-09-08 95 views
-1

请原谅标题中的含糊不清 - 我不太确定如何解释我的问题。高效的Python数据存储(抽象数据类型?)

给定一个字符串:

blah = "There are three cats in the hat" 

和(我不知道如何使用这个数据结构) “用户信息”:

cats -> ("tim", "1 infinite loop") 
three -> ("sally", "123 fake st") 
three -> ("tim", "1 infinite loop") 
three cats -> ("john", "123 fake st") 
four cats -> ("albert", "345 real road") 
dogs -> ("tim", "1 infinite loop") 
cats hat -> ("janet", NULL) 

正确的输出应该是:

tim (since 'cats' exists) 
sally (since 'three' exists) 
tim (since 'three' exists) 
john (since both 'three' and 'cats' exist) 
janet (since both 'cats' and 'hat' exist somewhere in the string blah) 

我想要一个有效的方式来存储这些数据。有可能匹配多个'三'字符串(即,150人将拥有该字符串)。我是否应该有一个包含所有这些数据的列表并复制“密钥”?

+1

我很困惑,你实际上试图在这里做。你能给一个简洁的英文解释你的算法和数据结构需要做什么吗? – 2009-09-08 20:47:24

+0

我相信字符串会自动实现在Python中,所以不要担心重复键。不是你应该反正。 150 *几个字节= diddly蹲。 – recursive 2009-09-08 21:00:55

+2

看起来你正在尝试做某种匹配规则,对吧? 所以,基本上,你有一个输入字符串“blah”。而且你有一系列匹配规则,对于每个匹配规则,如果左侧的每个单词都包含在字符串中,则右侧的名称(和地址)是输出的一部分。是对的吗? – jprete 2009-09-08 21:10:33

回答

0

我不知道你想要做什么,但也许你正在寻找的东西是这样的:

userinfo = { 
    "tim": "1 infinite loop", 
    "sally": "123 fake st", 
    "john": "123 fake st", 
    "albert": "345 real road", 
    "janet": None 
} 

conditions = { 
    "cats": ["tim"], 
    "three": ["sally", "tim"], 
    "three cats": ["john"], 
    "four cats": ["albert"], 
    "dogs": ["tim"], 
    "cats hat": ["janet"] 
} 

for c in conditions: 
    if all_words_are_in_the_sentence(c): 
    for p in conditions[c]: 
     print p, "because of", c 
     print "additional info:", userinfo[p] 
+0

你能提供'all_words_are_in_the_sentence'的实现吗? – 2009-09-08 23:52:47

+0

这个实现取决于OP实际想要在那里做什么,这在我原来的问题中并不清楚。在最简单的情况下,它可能是'blah.find(c)!= -1'。如果一切都应该基于单词,那么字典键应该已经被分成像'frozenset(['cats','hat'])'这样的单词。然后设置交集可以用来比较'set(blah.split())'。或者可以使用您的答案中的“匹配”功能。它确实取决于实际数据是最佳解决方案。 – sth 2009-09-09 00:16:39

1

我没有得到你真正尝试什么丝毫的线索但是如果你有很多数据,并且你需要存储它,并且你需要在其中搜索,那么具有索引功能的某种数据库似乎就是要走的路。

ZODB,CouchBD或SQL是一个趣味问题。我真的怀疑,无论如何,你需要关心磁盘空间的效率和搜索和查找的速度。

+0

Hooray for CouchDB! – 2009-09-08 21:13:58

6

像这样的东西?

class Content(object): 
    def __init__(self, content, maps_to): 
     self.content= content.split() 
     self.maps_to = maps_to 
    def matches(self, words): 
     return all(c in words for c in self.content) 
    def __str__(self): 
     return "%s -> %r" % (" ".join(self.content), self.maps_to) 

rules = [ 
    Content('cats',("tim", "1 infinite loop")), 
    Content('three',("sally", "123 fake st")), 
    Content('three',("tim", "1 infinite loop")), 
    Content('three cats',("john", "123 fake st")), 
    Content('four cats',("albert", "345 real road")), 
    Content('dogs',("tim", "1 infinite loop")), 
    Content('cats hat', ("janet", None)), 
] 

blah = "There are three cats in the hat" 

for r in rules: 
    if r.matches(blah.split()): 
     print r 

输出

cats -> ('tim', '1 infinite loop') 
three -> ('sally', '123 fake st') 
three -> ('tim', '1 infinite loop') 
three cats -> ('john', '123 fake st') 
cats hat -> ('janet', None)