1. 程式人生 > >小腳本--利用運算符重載簡化MongoDB的命令

小腳本--利用運算符重載簡化MongoDB的命令

每次 大於等於 while target nbsp method div break 括號

因為每次輸入MongoDB的命令都很復雜,老把自己繞迷糊了,所以寫了這個小腳本

哪裏有不正確,請多多指正。新手求教


1
class ff(object): 2 def __init__(self,qq): 3 self.qq = qq 4 def __gt__(self,qq):# > 5 return ff({$gt:{self.qq:qq.qq}}) 6 7 def __lt__(self,qq):# < 8 return ff({$lt:{self.qq:qq.qq}})
9 10 def __eq__(self,qq):# == 11 return ff({$eq:{self.qq:qq.qq}}) 12 13 def __and__(self,qq):# & 14 return ff({$and:[self.qq,qq.qq]}) 15 16 def __or__(self,qq):# | 17 return ff({$or:[self.qq,qq.qq]}) 18 19 def __le__(self, qq): # self <= rhs 小於等於
20 21 return ff({$lte:{self.qq:qq.qq}}) 22 23 def __ge__(self, qq):# self >= rhs 大於等於 24 25 return ff({$gte:{self.qq:qq.qq}}) 26 27 def __ne__(self, qq): # self != rhs 不等於 28 29 return ff({$ne:{self.qq:qq.qq}}) 30 31 def
__ior__(self, qq):# self |= rhs 即不也不 32 33 return ff({$nor:[self.qq,qq.qq]}) 34 35 def __invert__(self):# ~self 取反 36 return ff({$not:self.qq}) 37 38 # 類方法,將所有變量變成類ff類型的變量,以便於使用運算符重載 39 @classmethod 40 def oo(als,a): 41 i = 0 42 b = ‘‘ 43 c = ‘‘ 44 while i < len(a): 45 if a[i] not in "~!&|()><=": 46 while True: 47 if i == len(a)-1: 48 c += a[i] 49 b += ff( + c + ) 50 i+=1 51 break 52 elif a[i] in "~!&|()><=": 53 if c: 54 b += ff( + c + ) 55 c = ‘‘ 56 break 57 c += a[i] 58 i += 1 59 else: 60 b += a[i] 61 i+=1 62 63 # print(b) # 查看 64 return eval(b).qq 65 66 # a = "‘age‘>1" 67 # print(ff.oo(a)) 68 # a = "(‘age‘!=12)" 69 # print(ff.oo(a)) 70 # a = "(‘age‘==12)" 71 # print(ff.oo(a)) 72 # a = "(‘age‘>23)|(‘age‘<12)" 73 # print(ff.oo(a)) 74 # a = "(‘age‘>12)&(‘age‘<23)" 75 # print(ff.oo(a)) 76 # a = "~((‘age‘>12)&(‘age‘<23))" 77 # print(ff.oo(a)) 78 # a = "((‘age‘>12)&(‘age‘<23))|(‘score‘>90)" 79 # print(ff.oo(a))
80 if __name__ == __main__: 81 print("每個運算單獨用括號括起來,例如:((‘age‘>12)&(‘age‘<23))|(‘score‘>90)\n按ctrl + c 結束本程序",) 82 print() 83 while True: 84 a = input("請輸入:") 85 try: 86 print(ff.oo(a)) 87 except: 88 print("輸入有誤,請檢查!")

a = "‘age‘>1"
print(ff.oo(a))
a = "(‘age‘!=12)"
print(ff.oo(a))
a = "(‘age‘==12)"
print(ff.oo(a))
a = "(‘age‘>23)|(‘age‘<12)"
print(ff.oo(a))
a = "(‘age‘>12)&(‘age‘<23)"
print(ff.oo(a))
a = "~((‘age‘>12)&(‘age‘<23))"
print(ff.oo(a))
a = "((‘age‘>12)&(‘age‘<23))|(‘score‘>90)"
print(ff.oo(a))


# {$gt: {age: 1}}
# {$ne: {age: 12}}
# {$eq: {age: 12}}
# {$or: [{$gt: {age: 23}}, {$lt: {age: 12}}]}
# {$and: [{$gt: {age: 12}}, {$lt: {age: 23}}]}
# {$not: {$and: [{$gt: {age: 12}}, {$lt: {age: 23}}]}}
# {$or: [{$and: [{$gt: {age: 12}}, {$lt: {age: 23}}]}, {$gt:{score: 90}}]}

  

因為每次輸入MongoDB的命令都很復雜,老把自己繞迷糊了,所以寫了這個小腳本

哪裏有不正確,請多多指正。新手求教

轉載請註明出處https://www.cnblogs.com/BanL

小腳本--利用運算符重載簡化MongoDB的命令