2009-09-08 92 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)