今天其實是用來複習redis的,結果存儲單詞只用到了hash類型
數據來源
這個小遊戲的思路:
一. 先把單詞信息存在redis中(以hash類型)
- 從網上爬取單詞文本信息
- 讀取文本信息並將單詞和詞語分離
- 單詞和詞義分別作爲鍵和值存進redis中(field和value)
from redis import *
# 鏈接Redis
sr = StrictRedis(host="localhost", port=6379, db=0)
# html.text是爬取到的單詞信息
with open("html.text",'r') as f:
t = f.readlines()
# 判斷是否是中文,ord()返回字符的ascii碼
def ord_num(word):
return ord(word)<127
num = 1
for i in t:
n = 0
for j in i:
if ord_num(j):
n += 1
else:
break
key = i[0:n-1]
value = i[n:]
sr.hset(str(num),key, value)
num += 1
二.完成信息存儲後,開始編寫遊戲
- 鏈接redis服務器:
from redis import *
import random
sr = StrictRedis(host="localhost", port=6379, db=0)
- 在1~705中隨機生成四個數並轉換成字符類型(方便用redis索引):
index = [str(random.randint(1,705)) for i in range(4)]
- 根據隨機生成的字符向redis獲取信息:
for i in index:
word = {}
word['key'] = str(sr.hkeys(i)[0], encoding="utf-8")
word['value'] = sr.hvals(i)[0].decode().replace("\n","")
words.append(word)
- 生成選擇信息:
print("詞組“{}”的意思是:".format(words[0]["key"]))
ges_list = [0,1,2,3]
random.shuffle(ges_list)
print("a.{} b.{} c.{} d.{}".format(words[ges_list[0]]['value'],
words[ges_list[1]]['value'],
words[ges_list[2]]['value'],
words[ges_list[3]]['value']))
- 判斷選擇:
ges = input("選擇:")
if ges not in ans:
print("請選擇a、b、c、d")
print()
continue
if ges_list[pr[ges]] == 0:
print("選擇正確")
else:
print("錯。正確答案是{}".format(ans[ges_list.index(0)]))
print()
- 最後對代碼添加循環就完成小遊戲啦:
from redis import *
import random
sr = StrictRedis(host="localhost", port=6379, db=0)
pr = {i:j for i,j in zip(['a','b','c','d'],[0,1,2,3])}
ans = ['a','b','c','d']
while True:
index = [str(random.randint(1,705)) for i in range(4)]
words = []
for i in index:
word = {}
word['key'] = str(sr.hkeys(i)[0], encoding="utf-8")
word['value'] = sr.hvals(i)[0].decode().replace("\n","")
words.append(word)
print("詞組“{}”的意思是:".format(words[0]["key"]))
ges_list = [0,1,2,3]
random.shuffle(ges_list)
print("a.{} b.{} c.{} d.{}".format(words[ges_list[0]]['value'],
words[ges_list[1]]['value'],
words[ges_list[2]]['value'],
words[ges_list[3]]['value']))
ges = input("選擇:")
if ges not in ans:
print("請選擇a、b、c、d")
print()
continue
if ges_list[pr[ges]] == 0:
print("選擇正確")
else:
print("錯。正確答案是{}".format(ans[ges_list.index(0)]))
print()