Best Python code snippet using tappy_python
Canopy.py
Source:Canopy.py  
1import tabula2import PyPDF23from pdf2image import convert_from_path4import cv25import pytesseract6from pdfminer.converter import TextConverter7from PIL import Image8from pytesseract import Output9from pdfminer.converter import PDFPageAggregator10from pdfminer.layout import LAParams, LTFigure, LTTextBox11from pdfminer.pdfdocument import PDFDocument12from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager13from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed14from pdfminer.pdfparser import PDFParser15from io import StringIO16import xlsxwriter17filepath=r"C:/Users/raobk/Desktop/Python_Technical_Assignment/test_input.pdf"18images = convert_from_path("C:/Users/raobk/Desktop/Python_Technical_Assignment/test_input.pdf",poppler_path=r'C:/poppler-0.68.0/bin')19for i, image in enumerate(images):20    fname = 'image'+str(i)+'.png'21    image.save(fname, "PNG")22img = cv2.imread('image0.png')23gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)24threshold_img=cv2.threshold(gray_img,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]25pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'26custom_config = r'--oem 3 --psm 6'27d = pytesseract.image_to_data(threshold_img, output_type=Output.DICT, config = custom_config,lang='eng')28n_boxes = len(d['text'])29for i in range(n_boxes):30    try:31        if float(d['conf'][i]) > 60.0:32            (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])33            threshold_img = cv2.rectangle(threshold_img, (x, y), (x + w, y + h), (0, 255, 0), 2)34            # print(x,y)35    except ValueError as e:36        print(e)37# cv2.imshow('img', threshold_img)38# cv2.waitKey(0)39print(d['text'])40parse_text = []41word_list = []42last_word= ""43for word in d['text']:44    if word!="":45        word_list.append(word)46        last_word=word47    if(last_word!='' and word== '') or (word==d['text'][-1]):48        parse_text.append(word_list)49        word_list=[]50def convert_pdf_to_txt(path):51    rsrcmgr = PDFResourceManager()52    retstr = StringIO()53    codec = 'utf-8'54    laparams = LAParams()55    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)56    fp = open(path, 'rb')57    interpreter = PDFPageInterpreter(rsrcmgr, device)58    password = ""59    maxpages = 060    caching = True61    pagenos=set()62    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):63        interpreter.process_page(page)64    text = retstr.getvalue()65    fp.close()66    device.close()67    retstr.close()68    return text69stored=convert_pdf_to_txt(filepath)70gettingdata=stored.split("\n")71def check_if_empty(data):72    if data!= None and data!='':73        return False74    elif data=='' or data==" ":75        return True76# print(gettingdata)77added=[]78count=079for i in range(count,len(gettingdata)):80    try:81        if check_if_empty(gettingdata[i])==False and check_if_empty(gettingdata[i+1])==False:82            if gettingdata[i]!='Deposits':83                added.append(gettingdata[i]+gettingdata[i+1])84                if(len(gettingdata)==count):85                    count+=286        elif (check_if_empty(gettingdata[i])==False and check_if_empty(gettingdata[i-1])==True and check_if_empty(gettingdata[i+1])==True):87            added.append(gettingdata[i])88        if gettingdata[i]=='Deposits' and gettingdata[i+1]=="Deposits AUD":89            added.append(gettingdata[i])90            added.append(gettingdata[i+1])91    except:92        print("Error")93# print(added)94modifieddata=[]95for i in range(len(added)):96    if added[i]!=" ":97        modifieddata.append(added[i])98def is_integer_num(n):99    if isinstance(n, int):100        return True101    if isinstance(n, float):102        return n.is_integer()103    return False104# check(parse_text,storedata)105print(modifieddata)106new=[]107copy_text=parse_text108count=0109p=0110for i in range(len(copy_text)):111    if i==29:112        break113    for j in range(len(copy_text[i])):114        if len(copy_text[i])>1:115            if (int(len(copy_text[i])-1))==j or j>=int(len(copy_text[i])):116                break117            if(j>0):118                result4=copy_text[i][j-1][0].isupper()119            result1=copy_text[i][j][0].isupper()120            121            result2=copy_text[i][j+1][0].isupper()122            123            result3=copy_text[i][j+1][0+1].isupper()124            125            try:126                result7=copy_text[i][j+2][0].isupper()127            except:128                print('Error')129            try:130                if(count==2 and copy_text[i][j+2][0].isupper()==True and len(copy_text[i])==16):131                    for k in range(len(modifieddata)):132                        if copy_text[i][j]==modifieddata[k][:len(copy_text[i][j])]:133                            parse_text[i][j]=modifieddata[k]134                            parse_text[i].remove(parse_text[i][j+1])135                            parse_text[i].remove(parse_text[i][j+1])136                            parse_text[i].remove(parse_text[i][j+1])137                            parse_text[i].remove(parse_text[i][j+1])138                            parse_text[i].remove(parse_text[i][j+1])139                            parse_text[i].remove(parse_text[i][j+1])140                            parse_text[i].remove(parse_text[i][j+1])141                            parse_text[i].remove(parse_text[i][j+1])142                            parse_text[i].remove(parse_text[i][j+1])143                            parse_text[i].remove(parse_text[i][j+1])144                            parse_text[i].remove(parse_text[i][j+1])145                            parse_text[i].remove(parse_text[i][j+1])146                            parse_text.remove(parse_text[i+1])147                            print(parse_text)148                            count=0149                            p=1150                            break151            except:152                print("error")153            if(count==6 and result4==False and result7==True and len(copy_text[i])==9):154                parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]+" "+copy_text[i][j+2]+" "+copy_text[i][j+3]+" "+copy_text[i][j+4]+" "+copy_text[i][j+5]155                parse_text[i].remove(parse_text[i][j+1])156                parse_text[i].remove(parse_text[i][j+1])157                parse_text[i].remove(parse_text[i][j+1])158                parse_text[i].remove(parse_text[i][j+1])159                parse_text[i].remove(parse_text[i][j+1])160                print(parse_text)161                count=0162                break163            if(count==4 and result7==True and result4==False and len(copy_text[i])==9):164                parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]+" "+copy_text[i][j+2]+" "+copy_text[i][j+3]+" "+copy_text[i][j+4]+" "+copy_text[i][j+5]165                parse_text[i].remove(parse_text[i][j+1])166                parse_text[i].remove(parse_text[i][j+1])167                parse_text[i].remove(parse_text[i][j+1])168                parse_text[i].remove(parse_text[i][j+1])169                parse_text[i].remove(parse_text[i][j+1])170                print(parse_text)171                count=0172                break173            try:174                if(count==4 and copy_text[i][j+2][0].isupper()==True and len(copy_text[i])==15):175                    if(result7==True and result4==False and copy_text[i][j+2]=='GOLDMAN'):176                        copy_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]+" "+copy_text[i][j+2]+" "+copy_text[i][j+3]+" "+copy_text[i][j+4]+" "+copy_text[i][j+5]+" "+copy_text[i][j+6]+" "+copy_text[i][j+7]+" "+copy_text[i][j+8]+" "+copy_text[i][j+9]+" "+copy_text[i][j+10]+" "+copy_text[i][j+11]+" "+copy_text[i+1][0]+" "+copy_text[i+1][1]+" "+copy_text[i+1][2]177                        parse_text[i].remove(parse_text[i][j+1])178                        parse_text[i].remove(parse_text[i][j+1])179                        parse_text[i].remove(parse_text[i][j+1])180                        parse_text[i].remove(parse_text[i][j+1])181                        parse_text[i].remove(parse_text[i][j+1])182                        parse_text[i].remove(parse_text[i][j+1])183                        parse_text[i].remove(parse_text[i][j+1])184                        parse_text[i].remove(parse_text[i][j+1])185                        parse_text[i].remove(parse_text[i][j+1])186                        parse_text[i].remove(parse_text[i][j+1])187                        parse_text[i].remove(parse_text[i][j+1])188                        parse_text.remove(parse_text[i+1])189                        print(parse_text)190                        count=0191                        break192                    for k in range(len(modifieddata)):193                        if copy_text[i][j]==modifieddata[k][:len(copy_text[i][j])]:194                            parse_text[i][j]=modifieddata[k]195                            print(parse_text)196                            print(j)197                            print(copy_text[i])198                            parse_text[i].remove(parse_text[i][j+1])199                            parse_text[i].remove(parse_text[i][j+1])200                            parse_text[i].remove(parse_text[i][j+1])201                            parse_text[i].remove(parse_text[i][j+1])202                            parse_text[i].remove(parse_text[i][j+1])203                            parse_text[i].remove(parse_text[i][j+1])204                            parse_text[i].remove(parse_text[i][j+1])205                            parse_text[i].remove(parse_text[i][j+1])206                            parse_text[i].remove(parse_text[i][j+1])207                            parse_text[i].remove(parse_text[i][j+1])208                            parse_text[i].remove(parse_text[i][j+1])209                            210                            parse_text.remove(parse_text[i+1])211                            print(parse_text)212                            count=0213                            p=1214                            break215            except:216                print('Error')217            218            try:219                if(count==2 and result7==True and result4==False and len(copy_text[i])==15 and copy_text[i][j+3]=='HKD'):220                    parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]+" "+copy_text[i][j+2]+" "+copy_text[i][j+3]+" "+copy_text[i][j+4]+" "+copy_text[i][j+5]+" "+copy_text[i][j+6]+" "+copy_text[i][j+7]+" "+copy_text[i][j+8]+" "+copy_text[i][j+9]+" "+copy_text[i][j+10]+" "+copy_text[i][j+11]+" "+copy_text[i+1][0]+" "+copy_text[i+1][1]+" "+copy_text[i+1][2]+" "+copy_text[i+1][3]+" "+copy_text[i+1][4]+" "+copy_text[i+1][5]221                    parse_text[i].remove(parse_text[i][j+1])222                    parse_text[i].remove(parse_text[i][j+1])223                    parse_text[i].remove(parse_text[i][j+1])224                    parse_text[i].remove(parse_text[i][j+1])225                    parse_text[i].remove(parse_text[i][j+1])226                    parse_text[i].remove(parse_text[i][j+1])227                    parse_text[i].remove(parse_text[i][j+1])228                    parse_text[i].remove(parse_text[i][j+1])229                    parse_text[i].remove(parse_text[i][j+1])230                    parse_text[i].remove(parse_text[i][j+1])231                    parse_text[i].remove(parse_text[i][j+1])232                    parse_text.remove(parse_text[i+1])233                    print(parse_text)234                    count=0235                  236                    break237                    238            except:239                print('Error')240            241            try:242                if(count==4 and len(copy_text[i])==18 and result4==False):243                    for k in range(len(modifieddata)):244                        if copy_text[i][j]==modifieddata[k][:len(copy_text[i][j])]:245                            parse_text[i][j]=modifieddata[k]246                            parse_text[i].remove(parse_text[i][j+1])247                            parse_text[i].remove(parse_text[i][j+1])248                            parse_text[i].remove(parse_text[i][j+1])249                            parse_text[i].remove(parse_text[i][j+1])250                            parse_text[i].remove(parse_text[i][j+1])251                            parse_text[i].remove(parse_text[i][j+1])252                            parse_text[i].remove(parse_text[i][j+1])253                            parse_text[i].remove(parse_text[i][j+1])254                            parse_text[i].remove(parse_text[i][j+1])255                            parse_text[i].remove(parse_text[i][j+1])256                            parse_text[i].remove(parse_text[i][j+1])257                            parse_text[i].remove(parse_text[i][j+1])258                            parse_text[i].remove(parse_text[i][j+1])259                            parse_text[i].remove(parse_text[i][j+1])260                            count=0261                            p=1262                            break263            except:264                print('Error')265            try:266                if(count==2 and len(copy_text[i])==15 and result4==False and copy_text[i][j]=='CONSENT'):267                    for k in range(len(modifieddata)):268                        if copy_text[i][j]==modifieddata[k][:len(copy_text[i][j])]:269                            parse_text[i][j]=modifieddata[k]270                            parse_text[i].remove(parse_text[i][j+1])271                            parse_text[i].remove(parse_text[i][j+1])272                            parse_text[i].remove(parse_text[i][j+1])273                            parse_text[i].remove(parse_text[i][j+1])274                            parse_text[i].remove(parse_text[i][j+1])275                            parse_text[i].remove(parse_text[i][j+1])276                            parse_text[i].remove(parse_text[i][j+1])277                            parse_text[i].remove(parse_text[i][j+1])278                            parse_text[i].remove(parse_text[i][j+1])279                            parse_text[i].remove(parse_text[i][j+1])280                            parse_text[i].remove(parse_text[i][j+1])281                            count=0282                            p=1283                            break284            except:285                print('Error')286                          287                    288            try:289                result5=is_integer_num(int(copy_text[i][j]))290                result6=is_integer_num(int(copy_text[i][j+2]))291                if(result5==True and result2==True and result6==True):292                    parse_text[i][j]=copy_text[i][j]+ " " +copy_text[i][j+1] + " "+copy_text[i][j+2]293                    parse_text[i].remove(parse_text[i][j+1])294                    parse_text[i].remove(parse_text[i][j+1])295                    count+=1296                    print(count)297                    print(parse_text)298            except:299                print('Error')300            301            if(result1==True and result2==False and result3==False):302                parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]303                parse_text[i].remove(parse_text[i][j+1])304                print(parse_text)305                306            elif(j >0 and result4==True and result1==False):307                parse_text[i][j]=copy_text[i][j-1]+" "+copy_text[i][j]308                parse_text[i].remove(parse_text[i][j-1])309                        # copy_text[i].remove(copy_text[i][j+1])310                print(parse_text)311            elif(result1==True and result2==True and result3==True):312                if p==0:313                    if result4==False and result7==True:314                        parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]+ " "+ copy_text[i][j+2] + " "+ copy_text[i][j+3]315                        if(count==4 and len(copy_text[i])==8 and result4==False):316                            parse_text[i][j+4]=copy_text[i][j+4]+copy_text[i][j+5]317                            parse_text[i].remove(parse_text[i][j+5])318                        if(count==2 and len(copy_text[i])==8 and result4==False):319                            parse_text[i][j+4]=copy_text[i][j+4]+copy_text[i][j+5]320                            parse_text[i].remove(parse_text[i][j+5])321                        parse_text[i].remove(parse_text[i][j+1])322                        parse_text[i].remove(parse_text[i][j+1])323                        parse_text[i].remove(parse_text[i][j+1])324                        print(parse_text)325                    else:326                        parse_text[i][j]=copy_text[i][j]+" "+copy_text[i][j+1]327                        parse_text[i].remove(parse_text[i][j+1])328                    # copy_text[i].remove(copy_text[i][j+1])329                        print(parse_text)330                else:331                    p=0332                    break333            334print(parse_text)335raised=0336currency=''337for i in range(len(parse_text)):338    if i==25:339        break340    for j in range(len(parse_text[i])):341        if(parse_text[i][j]=="Opening balance"):342            if(parse_text[i+1][j-1][:9]=="Month end"):343                parse_text.remove(parse_text[i])344                parse_text.remove(parse_text[i])345        print(parse_text[i][j])346        if(parse_text[i][j][3:6]=='Mar'):347            print(parse_text[i][j])348            parse_text[i][j]=parse_text[i][j][7:]+"-"+"03"+"-"+parse_text[i][j][:2]349            print(parse_text[i][j])350        elif(parse_text[i][j][3:6]=='Feb'):351            print(parse_text[i][j])352            parse_text[i][j]=parse_text[i][j][7:]+"-"+"02"+"-"+parse_text[i][j][:2]353            print(parse_text[i][j])354print(parse_text)355for i in range(len(parse_text)):356    if(i==20):357        break358    for j in range(len(parse_text[i])):359        print(parse_text[i][j])360        361        if(parse_text[i][j]=='Transaction details'):362            parse_text.remove(parse_text[i])363        if(parse_text[i][j]=='Deposits'):364            parse_text.remove(parse_text[i])365        if(parse_text[i][j]=='Deposits HKD'):366            raised=1367            currency=parse_text[i][j][9:]368            parse_text.remove(parse_text[i])369            print(parse_text)370        if(parse_text[i][j-1]=='Deposits USD'):371            raised=1372            currency=parse_text[i][j-1][9:]373            print(parse_text)374            parse_text.remove(parse_text[i])375        if(raised==1 and currency=="USD"):376            parse_text[i].insert(len(parse_text[i])-1,'USD')377            print(parse_text)378            break379        if(raised==1 and currency=='HKD'):380            if(parse_text[i][j][:9]=="Month end"):381                raised=0382                currency=''383                parse_text.remove(parse_text[i])384                continue385            parse_text[i].insert(len(parse_text[i])-1,'HKD')386            print(parse_text)387            break388def keysearch(keywords):389    list1=[]390    for i in range(len(parse_text)):391        for j in range(len(parse_text[i])):392            if parse_text[i][j]==keywords:393                list1.append(i) 394    return list1395jump=0396for i in range(len(parse_text)):397    if(jump==1):398        energy=energy-1399        print(energy)400        if(energy==0):401            jump=0402            continue403    for j in range(len(parse_text[i])):404        print(parse_text[i])405        keyword=parse_text[i][0]406        # print(keyword)407        getval=keysearch(keyword)408        updating=list(set(getval))409        if(jump==0):410            energy=len(updating)-1411        if(len(updating)>1 and jump==0):412            maximum=max(updating)413            minimum=min(updating)414            diff=maximum-minimum415            if(diff>2 and jump==0):416                value1=parse_text[maximum][len(parse_text[maximum])-1]417                value2=parse_text[minimum][len(parse_text[minimum])-1]418                try:419                    if(float(value1)>float(value2)):420                        parse_text.insert(minimum+1,parse_text[maximum])421                        parse_text.pop(maximum+1)422                        print(parse_text)423                        jump=1424                except:425                    if(value1[0]=='(' and value1[-1]==')' and is_integer_num(int(value1[1]))==True):426                        value1=value1.replace(",","")427                        value2=value2.replace(",","")428                        if(float(value1[1:-1])<float(value2)):429                            parse_text.insert(minimum,parse_text[maximum])430                            parse_text.pop(maximum+1)431                            print(parse_text)432                            jump=1433                    elif(value2[0]=='(' and value2[-1]==')' and is_integer_num(int(value2[1]))==True):434                        modif=value2[1:-1]435                        modif=modif.replace(",","")436                        print(modif)437                        value1=value1.replace(",","")438                        print(value1)439                        if(float(modif)>float(value1)):440                            parse_text.insert(minimum,parse_text[maximum])441                            parse_text.pop(maximum+1)442                            print(parse_text)443                            jump=1444                        445                        print(parse_text[i])446        break447for i in range(len(parse_text)):448    for j in range(len(parse_text[i])):449        if(parse_text[i][j]=='Amount'):450            parse_text[i][j]='Currency'451            parse_text[i].insert(j+1,'Debit')452            parse_text[i].insert(j+2,'Credit')453        data=parse_text[i][len(parse_text[i])-1]454        try:455            if(is_integer_num(int(data[0]))==True and is_integer_num(int(data[-1]))==True):456                data=data.replace(",","")457                parse_text[i][len(parse_text[i])-1]=float(data)458                print(is_integer_num(parse_text[i][j]))459                parse_text[i].insert((len(parse_text[i]))-1,'')460                break461        except:462            if(data[0]=='(' and data[-1]==')' and is_integer_num(int(data[1]))==True):463                d1=parse_text[i][len(parse_text[i])-1][1:-1]464                data=d1.replace(",","")465                parse_text[i][len(parse_text[i])-1]=float(data)466                parse_text[i].insert((len(parse_text[i])),'')467                break468            print('Error')469print(parse_text)            470book = xlsxwriter.Workbook('Canopy.xlsx')471sheet = book.add_worksheet()472for i in range(len(parse_text)):473    for j in range(len(parse_text[i])):474        sheet.write(i,j,parse_text[i][j])475book.close()476cv2.imshow('img', threshold_img)...cribbage_test.py
Source:cribbage_test.py  
...25        self.game = crib.Cribbage(self.human, 'no-cut no-pick')26        self.game.set_up()27    def testFifteenDouble(self):28        """Test scoring 15s with a card working double."""29        hand = self.game.deck.parse_text('5S 4S 6D 3H KC')30        self.assertEqual(2, self.game.score_fifteens(hand))31    def testFifteenFive(self):32        """Test scoring 15 with five cards."""33        hand = self.game.deck.parse_text('AS 4S 2D 3H 5C')34        self.assertEqual(1, self.game.score_fifteens(hand))35    def testFifteenMax(self):36        """Test scoring four 15s."""37        hand = self.game.deck.parse_text('5S TS QD JH KC')38        self.assertEqual(4, self.game.score_fifteens(hand))39    def testFifteenPair(self):40        """Test scoring 15 with two cards."""41        hand = self.game.deck.parse_text('AS 3S 5S 8S JS')42        self.assertEqual(1, self.game.score_fifteens(hand))43    def testFifteenQuad(self):44        """Test scoring 15 with four cards."""45        hand = self.game.deck.parse_text('AS 4S 2D 3H 7C')46        self.assertEqual(1, self.game.score_fifteens(hand))47    def testFifteenTen(self):48        """Test scoring 15 with a face card and a five."""49        hand = self.game.deck.parse_text('2S 5S 2D 7H QC')50        self.assertEqual(1, self.game.score_fifteens(hand))51    def testFifteenTrip(self):52        """Test scoring 15 with three cards."""53        hand = self.game.deck.parse_text('AS 4S 5S 6H 7C')54        self.assertEqual(1, self.game.score_fifteens(hand))55    def testFifteenTwice(self):56        """Test scoring 15s with two sets of cards."""57        hand = self.game.deck.parse_text('5S 4S 8H 3H KC')58        self.assertEqual(2, self.game.score_fifteens(hand))59    def testFlushFive(self):60        """Test a five card flush in a hand."""61        hand = self.game.deck.parse_text('AS 3S 5S 8S')62        self.game.starter = self.game.deck.parse_text('JS')63        self.game.hands = {'The Crib': []}64        self.assertEqual(5, self.game.score_flush(hand))65    def testFlushFiveCrib(self):66        """Test scoring a five card flush in the crib."""67        hand = self.game.deck.parse_text('AS 3S 5S 8S')68        self.game.starter = self.game.deck.parse_text('JS')69        self.game.hands = {'The Crib': hand}70        self.assertEqual(5, self.game.score_flush(hand))71    def testFlushFour(self):72        """Test a four card flush in a hand."""73        hand = self.game.deck.parse_text('AS 3S 5S 8S')74        self.game.starter = self.game.deck.parse_text('JC')75        self.game.hands = {'The Crib': []}76        self.assertEqual(4, self.game.score_flush(hand))77    def testFlushFourCrib(self):78        """Test not scoring a four card flush in the crib."""79        hand = self.game.deck.parse_text('AS 3S 5S 8S')80        self.game.starter = self.game.deck.parse_text('JC')81        self.game.hands = {'The Crib': hand}82        self.assertEqual(0, self.game.score_flush(hand))83    def testFlushFourNot(self):84        """Test not scoring a four card flush made with the starter card."""85        hand = self.game.deck.parse_text('AS 3C 5S 8S')86        self.game.starter = self.game.deck.parse_text('JS')87        self.game.hands = {'The Crib': []}88        self.assertEqual(0, self.game.score_flush(hand))89    def testMaximum(self):90        """Test scoring the best possible hand)."""91        hand = self.game.deck.parse_text('5D 5C 5H JS')92        self.game.starter = self.game.deck.parse_text('5S')93        self.game.double_pairs = False94        self.assertEqual(29, self.game.score_one_hand(hand, 'Bob'))95    def testNob(self):96        """Test scoring his nob (jack of the starter suit)."""97        hand = self.game.deck.parse_text('AS 3C 7S JS')98        self.game.starter = self.game.deck.parse_text('9S')99        self.game.double_pairs = False100        self.assertEqual(1, self.game.score_one_hand(hand, 'Bob'))101    def testNothing(self):102        """Test scoring a worthless hand."""103        hand = self.game.deck.parse_text('4S 7C 9S QS')104        self.game.starter = self.game.deck.parse_text('TS')105        self.game.double_pairs = False106        self.assertEqual(0, self.game.score_one_hand(hand, 'Bob'))107    def testPairDouble(self):108        """Test scoring three of a kind with doubled pairs."""109        hand = self.game.deck.parse_text('AD 3C 8H 8S 8C')110        self.game.double_pairs = True111        self.assertEqual([('8', 3, 12)], self.game.score_pairs(hand))112    def testPairFour(self):113        """Test scoring four of a kind."""114        hand = self.game.deck.parse_text('8D 3C 8H 8S 8C')115        self.game.double_pairs = False116        self.assertEqual([('8', 4, 12)], self.game.score_pairs(hand))117    def testPairFull(self):118        """Test scoring a full house."""119        hand = self.game.deck.parse_text('3D 3C 8H 8S 8C')120        self.game.double_pairs = False121        self.assertEqual(set([('8', 3, 6), ('3', 2, 2)]), set(self.game.score_pairs(hand)))122    def testPairNot(self):123        """Test scoring no pairs."""124        hand = self.game.deck.parse_text('AD 3C 5H JS 8C')125        self.game.double_pairs = False126        self.assertEqual([], self.game.score_pairs(hand))127    def testPairOne(self):128        """Test scoring one pair."""129        hand = self.game.deck.parse_text('AD 3C 5H 8S 8C')130        self.game.double_pairs = False131        self.assertEqual([('8', 2, 2)], self.game.score_pairs(hand))132    def testPairThree(self):133        """Test scoring three of a kind."""134        hand = self.game.deck.parse_text('AD 5C 8H 8S 8C')135        self.game.double_pairs = False136        self.assertEqual([('8', 3, 6)], self.game.score_pairs(hand))137    def testPairTwo(self):138        """Test scoring two distinct pairs."""139        hand = self.game.deck.parse_text('AD 5C 5H 8S 8C')140        self.game.double_pairs = False141        self.assertEqual(set([('5', 2, 2), ('8', 2, 2)]), set(self.game.score_pairs(hand)))142    def testRunFive(self):143        """Test scoring a five card run."""144        hand = self.game.deck.parse_text('8D 5C 6H 7S 9C')145        self.assertEqual([(5, 1)], self.game.score_runs(hand))146    def testRunFour(self):147        """Test scoring a four card run."""148        hand = self.game.deck.parse_text('8D 6C 5H 7S JC')149        self.assertEqual([(4, 1)], self.game.score_runs(hand))150    def testRunFourTwo(self):151        """Test scoring a four card run twice."""152        hand = self.game.deck.parse_text('8D 6C 5H 7S 5C')153        self.assertEqual([(4, 2)], self.game.score_runs(hand))154    def testRunFourFour(self):155        """Test scoring a four card run four times."""156        hand = self.game.deck.parse_text('8D 6C 5H 7S 5C 8S')157        self.assertEqual([(4, 4)], self.game.score_runs(hand))158    def testRunThree(self):159        """Test scoring a three card run."""160        hand = self.game.deck.parse_text('5C AD 6H 9C 7S')161        self.assertEqual([(3, 1)], self.game.score_runs(hand))162    def testRunThreeEight(self):163        """Test scoring a three card run eight times."""164        hand = self.game.deck.parse_text('5C 7D 6H 6C 7S 5D')165        self.assertEqual([(3, 8)], self.game.score_runs(hand))166    def testRunThreeFour(self):167        """Test scoring a three card run four times."""168        hand = self.game.deck.parse_text('7H 5C 7D 6H 7C 7S')169        self.assertEqual([(3, 4)], self.game.score_runs(hand))170    def testRunThreeSix(self):171        """Test scoring a three card run six times."""172        hand = self.game.deck.parse_text('5C 7D 6H 6C 7S 7H')173        self.assertEqual([(3, 6)], self.game.score_runs(hand))174    def testRunThreeTwice(self):175        """Test scoring two three card runs."""176        hand = self.game.deck.parse_text('5C 7D TH 6C QS JH')177        self.assertEqual([(3, 1), (3, 1)], self.game.score_runs(hand))178    def testRunTwo(self):179        """Test not scoring a two card run."""180        hand = self.game.deck.parse_text('5C 2D TH 6C QS 8H')181        self.assertEqual([], self.game.score_runs(hand))182    def testRunTwoTwoHigh(self):183        """Test not scoring a two card run two times on the high side."""184        hand = self.game.deck.parse_text('5C 2D TH 6C 6S 8H')185        self.assertEqual([], self.game.score_runs(hand))186    def testRunTwoTwoLow(self):187        """Test not scoring a two card run two times on the low side."""188        hand = self.game.deck.parse_text('5C 2D TH 6C QS 5H')189        self.assertEqual([], self.game.score_runs(hand))190    def testRunTwoTwice(self):191        """Test not scoring two two card run."""192        hand = self.game.deck.parse_text('5C 2D TH 6C QS 9H')193        self.assertEqual([], self.game.score_runs(hand))194class ScorePeggingTest(unittest.TestCase):195    """Test scoring cribbage plays. (unittest.TestCase)"""196    def setUp(self):197        self.human = unitility.AutoBot([5, 23, 108, 801])198        self.game = crib.Cribbage(self.human, 'none')199        self.game.set_up()200    def testFifteen(self):201        """Test pegging to 15."""202        self.game.in_play['Play Sequence'].cards = [self.game.deck.parse_text('5C')]203        play = self.game.deck.parse_text('JS')204        self.game.card_total = 5205        message = '{} scores 2 points for reaching 15.'.format(self.human.name)206        self.assertEqual((2, message), self.game.score_sequence(self.human, play))207    def testFourKind(self):208        """Test pegging four of a kind."""209        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('6C 6D 6H')210        play = self.game.deck.parse_text('6S')211        message = '{} scores 12 points for getting four cards of the same rank.'.format(self.human.name)212        self.assertEqual((12, message), self.game.score_sequence(self.human, play))213    def testNothing(self):214        """Test pegging nothing."""215        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('4H 2C 3D')216        play = self.game.deck.parse_text('7S')217        self.game.card_total = 9218        self.assertEqual((0, ''), self.game.score_sequence(self.human, play))219    def testPair(self):220        """Test pegging a pair."""221        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('5H 6C')222        play = self.game.deck.parse_text('6S')223        message = '{} scores 2 points for getting two cards of the same rank.'.format(self.human.name)224        self.assertEqual((2, message), self.game.score_sequence(self.human, play))225    def testStraightFive(self):226        """Test pegging a five card straight."""227        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('4H 2C 5S 3D')228        play = self.game.deck.parse_text('6C')229        message = '{} scores 5 points for getting a five-card straight.'.format(self.human.name)230        self.assertEqual((5, message), self.game.score_sequence(self.human, play))231    def testStraightFour(self):232        """Test pegging a four card straight."""233        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('4H 2C 3D')234        play = self.game.deck.parse_text('5S')235        message = '{} scores 4 points for getting a four-card straight.'.format(self.human.name)236        self.assertEqual((4, message), self.game.score_sequence(self.human, play))237    def testStraightThree(self):238        """Test pegging a four card straight."""239        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('2C 3D')240        play = self.game.deck.parse_text('4H')241        message = '{} scores 3 points for getting a three-card straight.'.format(self.human.name)242        self.assertEqual((3, message), self.game.score_sequence(self.human, play))243    def testThirtyOne(self):244        """Test pegging to 31."""245        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('4H 2C 5S 3D QC')246        play = self.game.deck.parse_text('7C')247        self.game.card_total = 24248        message = '\nThe count has reached 31.\n{} scores 2 points for reaching 31.'249        message = message.format(self.human.name)250        self.assertEqual((2, message), self.game.score_sequence(self.human, play))251    def testTrip(self):252        """Test pegging three of a kind."""253        self.game.in_play['Play Sequence'].cards = self.game.deck.parse_text('6C 6D')254        play = self.game.deck.parse_text('6S')255        message = '{} scores 6 points for getting three cards of the same rank.'.format(self.human.name)256        self.assertEqual((6, message), self.game.score_sequence(self.human, play))257if __name__ == '__main__':...corenlp.py
Source:corenlp.py  
1from pycorenlp import StanfordCoreNLP2from tqdm import tqdm3import matplotlib.pyplot as plt4import re5class CoreNLP():6    def __init__(self):7        self.nlp=StanfordCoreNLP('http://localhost:9000')8        self.interro_list=["WHNP","WHADVP","WRB","WHADJP","WDT","WP","WP$","WRB"]9        self.count=-110    #åè©ãå«ã¾ãããã®ãã§ãã¯11    def verb_check(self,token_list):12        for token in token_list:13            pos=token["pos"]14            if "VB" in pos:15                return True16        return False17    #textã®çåè©å¥ãæ½åºãã18    #çåè©å¥ã®ãªã¹ãã¨ããã以å¤ã®åèªã®ãªã¹ããè¿ã19    def forward(self,text):20        q=self.nlp.annotate(text, properties={'annotators': 'tokenize,ssplit,parse','outputFormat': 'json'})21        tokens=q["sentences"][0]["tokens"]              #æã®ä¸ã®åèª22        deps=q["sentences"][0]["basicDependencies"]     #ä¾åé¢ä¿ï¼ä½¿ããªãï¼23        parse_text=q["sentences"][0]["parse"]           #奿§é ã®ãã¼ã¹çµæ24        token_list=[{"index":token["index"],"text":token["originalText"],"pos":token["pos"]} for token in tokens]25        parse_text=parse_text.replace("(","( ").replace(")"," )").split()26        WP_list=[]      #çåè©å¥ã«å«ã¾ããåèª27        NotWP_list=[]   #çåè©å¥ã«å«ã¾ããªãåèª28        WP_flag=False   #çåè©å¥ãçºè¦æ¸ã¿ãªãTrue29        depth=030        for i in range(len(parse_text)-1):31            #depthã0ã®å ´åãã¤ãï¼çåè©ã®å¥æ§é ã«æªçªå
¥ãã¾ãã¯ããã§ã«çåè©ãè¦ã¤ãã£ã¦ããï¼32            if depth==0 and (parse_text[i] not in self.interro_list or WP_flag==True):33                if parse_text[i]!=")" and parse_text[i+1]==")":34                    NotWP_list.append(parse_text[i])35                continue36            #çåè©ã®å¥æ§é ã®å
é¨ã«ããæ37            else:38                WP_flag=True39                depth=max(depth,1)40                if parse_text[i]=="(":41                    depth+=142                elif parse_text[i]==")":43                    depth-=144                if parse_text[i]!=")" and parse_text[i+1]==")":45                    WP_list.append(parse_text[i])46        return WP_list,NotWP_list47    #çåè©å¥ãçåè©å¥ä»¥å¤ãåè©ã®æç¡ãè¿ã48    def forward_verbcheck(self,text):#input:(batch,seq_len)49        q=self.nlp.annotate(text, properties={'annotators': 'tokenize,ssplit,parse','outputFormat': 'json'})50        tokens=q["sentences"][0]["tokens"]              #æã®ä¸ã®åèª51        deps=q["sentences"][0]["basicDependencies"]     #ä¾åé¢ä¿ï¼ä½¿ããªãï¼52        parse_text=q["sentences"][0]["parse"]           #奿§é ã®ãã¼ã¹çµæ53        token_list=[{"index":token["index"],"text":token["originalText"],"pos":token["pos"]} for token in tokens]54        parse_text=parse_text.replace("(","( ").replace(")"," )").split()55        WP_list=[]      #çåè©å¥ã«å«ã¾ããåèª56        NotWP_list=[]   #çåè©å¥ã«å«ã¾ããªãåèª57        WP_flag=False   #çåè©å¥ãçºè¦æ¸ã¿ãªãTrue58        #çåè©å¥ã®æ¢ç´¢59        depth=060        for i in range(len(parse_text)-1):61            #depthã0ã®å ´åãã¤ãï¼çåè©ã®å¥æ§é ã«æªçªå
¥ãã¾ãã¯ããã§ã«çåè©ãè¦ã¤ãã£ã¦ããï¼62            if depth==0 and (parse_text[i] not in self.interro_list or WP_flag==True):63                if parse_text[i]!=")" and parse_text[i+1]==")":64                    NotWP_list.append(parse_text[i])65                continue66            #çåè©ã®å¥æ§é ã®å
é¨ã«ããæ67            else:68                WP_flag=True69                depth=max(depth,1)70                if parse_text[i]=="(":71                    depth+=172                elif parse_text[i]==")":73                    depth-=174                if parse_text[i]!=")" and parse_text[i+1]==")":75                    WP_list.append(parse_text[i])76        vb=self.verb_check(token_list)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
