Small try sledgehammer simple idiom solitaire.
Ideas--
1. Download the TXT version of the idiom dictionary online
2, through the processing of Python to get the format of the idiom, and organized into a dictionary (Python Dictionary lookup speed)
3, the Python program, find the last word entered by the user and the first word in the dictionary, put in the list, and randomly selected by random, and then output
Dictionary finishing section: converting to Dictionaries
File = Open (r'D:\Desktop\zidian.txt'). ReadLines () F= Open (R'D:\Desktop\zidian3.txt','W') x={}num=0 forIinchFile:PrintI[2:10] X[num]= I[2:10] F.write ("'%s ': U '%s ', \ n"% (num,i[2:10]) Num+=1f.close ()
Convert to dictionary-similar format
Chengyu = {
' 0 ': U ' a party than week ',
' 1 ': U ' appin juedao ',
' 2 ': U ' Aquan ',
' 3 ': U ' A-time tending to the vulgar ',
' 4 ': U ' a kitsch ',
' 5 ': U ' o ' ...}
Judgment part: Get the idiom through input, then intercept the last word, look for the idiom in the dictionary beginning with the word, and output. Add try,except to prevent the wrong idiom from being found. (Dictionary not complete, only 20000 + data)
While 1: list = [] s =raw_input (' Please enter idiom: ') ns = S.decode (' GBK ') [-1:] try: For I in Chengyu.values (): ni = i[:1] if ns = = ni: list.append (i) print U ' solitaire: ', Len (list), Random.choice (list) except: print U ' Solitaire: It's under the loss '
: No optimized processing, no judgment on whether the user entered the correct idiom.
The program is relatively simple, the main difficulty lies in the conversion of the code, puzzled for a long time.
1, when judging whether the word is equal, if the encoding format is inconsistent, it can not be compared, error occurs. STR is GBK encoded, first decoded into Unicode, and then compared.
2. If you do not know the encoding, you can use Isinstance (s, Unicode) to determine, or import chardet, and then use the Chardet.detect (TestData) query format
3, first decoding S.decode (' GBK ') [-1:], and S[-1:].decode (' GBK ') is not the same effect, the former is correct, the latter will be wrong
python--Idioms Solitaire Mini Game