230 likes | 310 Views
A Censor Class. class Censor : def __ init __ ( self,replacers ='!@$%&?', badwords =[]): self.badwords = badwords self.replacers = replacers
E N D
A Censor Class class Censor:def__init__(self,replacers='!@$%&?', badwords=[]):self.badwords = badwordsself.replacers = replacers definput_badwords(self,fpath):# build the self.badwordslist from file of whitespace # separated wordsf = open(fpath,'r')S = f.read()f.close()self.badwords = S.split() defoutput_badwords(self,fpath):# store the self.badwordslist in file, #separated by spaces S = ' '.join(self.badwords)f = open(fpath,'w') f.write(S)f.close()
A Censor Class defaddwords(self,word_list):# add words from word_list to self.badwordsself.badwords= self.badwords+word_list # or: self.badwords.extend(word_list) defremove_words(self,word_list):# remove words in word_list from self.badwordsself.badwords= [w for w in self.badwords if w not in word_list] # or:#for w in word_list:#while w in self.badwords:#self.badwords.remove(w)
A Censor Class defcensor_word(self,n)# return a length-n word composed of randomly chosen# symbols from self.replacers w = ''for i in range(n):w += random.choice(self.repeaters)return w defcensor_word2(self,n):# return a length-n word composed of randomly chosen# symbols from self.replacers, no two consecutive letters the samew = random.choice(self.repeaters)for i in range(n-1):new = random.choice(self.repeaters)while new == w[-1]:new = random.choice(self.repeaters)w += newreturn w defcensor_file(self,fpath):# Write a new file named fpath+'.censored' whose contents are the contents of the # file at fpathwith each word that is in self.badwordsreplaced by an equal-length # word of randomlychosen letters from self.replacerspass
A Censor Class defcensor_file(self,fpath):# Write a new file named fpath+'.censored' whose contents are the contents of the # file at fpathwith each word that is in self.badwordsreplaced by an equal-length # word of randomlychosen letters from self.replacers inf= open(fpath,'r')L = inf.read().split()inf.close() K = []for w in L: if w in self.badwords:K.append(censor_word(len(w))) else:K.append(w) outf = open(fpath+'.censored','w')outf.write(' '.join(K))outf.close() badword_filename = input("Enter the name of the bad words file: ")txt_filename= input("Enter the name of the file to be censored: ") C = Censor() C.input_badwords(badword_filename)C.censor_file(txt_filename)
The Card Class # card.py# defines a minimal class to represent poker cards class Card:'''Represents cards from a poker deck. The rank is an integer between 1 and 13 and the suit is one of 'c','d','h','s'. ''' def__init__(self,rank,suit):self.rank = rankself.suit = suit defgetRank(self):return self.rank defgetSuit(self):return self.suit
The Card Class # Card class definition continued defBJValue(self): # Blackjack card valueif self.rank <= 10:return self.rankelse:return 10
The Card Class # Card class definition continued def__str__(self): # string to be printed when the card s = '' # appears in a print statement if self.rank == 1:s += 'Ace' elif 2 <= self.rank <= 10:s += str(self.rank) elifself.rank == 11:s += 'Jack' elifself.rank == 12:s += 'Queen' else:s += 'King' s += ' of '
The Card Class # Card class definition continued # def__str__(self) continuedif self.suit == 'c':s += 'Clubs' elifself.suit == 'd':s += 'Diamonds' elifself.suit == 'h':s += 'Hearts' else:s += 'Spades' return s
The Card Class # Card class definition continueddef__lt__(self,other): # Makes possible comparison via < if self.rank == other.rank:return self.suit < other.suit elifself.rank == 1:return False elifother.rank == 1:return True else:return self.rank < other.rank def__ eq__(self,other): # Makes possible comparison via ==return self.rank == other.rank and \self.suit== other.suit
The Hand Class # poker_hand.py# class to represent a hand occurring in a poker game from card import Card class Hand: def__init__(self,card_list): self.cards = card_list# must have length 5 defmaxRank(self): # returns a card of maximum rank in self.card_list # if more than one card has that rank, returns the # card with the highest suit # where 'c' < 'd' < 'h' < 's' # (which is just the alphabetic order!) return sorted(self.cards)[-1]
The Hand Class defpoker_description(self): # returns one of the following strings: # 'Royal Flush','StraightFlush','Fourof a Kind', # 'Full House','Flush', 'Straight', 'Three of a Kind', # 'Two Pair','Pair', 'High Card' is_flush= len({c.getSuit() for c in self.cards}) ==1 high_card = self.maxRank() high_rank = high_card.getRank() rank_list= sorted([c.getRank() for c in self.cards]) if rank_list == list(range(high_rank-4,high_rank+1)): is_straight = True elifrank_list == [1,10,11,12,13]: is_straight = True else: is_straight = False
The Hand Class # poker_description definition continued is_flush= len({c.getSuit() for c in self.cards}) ==1 high_card = self.maxRank() high_rank = high_card.getRank() rank_list= sorted([c.getRank() for c in self.cards]) if rank_list == list(range(high_rank-4,high_rank+1)): is_straight = True elifrank_list == [1,10,11,12,13]: is_straight = True else: is_straight = False
The Hand Class # poker_description definition continued if is_flush and is_straight: if high_rank == 1: return "Royal Flush" else: return "Straight Flush" if is_flush: return "Flush" if is_straight: return "Straight"
The Hand Class # poker_description definition continued rank_counts= sorted([rank_list.count(k) for k in set(rank_list)]) if rank_counts == [1,4]: return "Four of a Kind" elifrank_counts == [2,3]: return "Full House" elifrank_counts == [1,1,3]: return "Three of a Kind" elifrank_counts == [1,2,2]: return "Two Pair" elifrank_counts == [1,1,1,2]: return "Pair" else: return "High Card" def__str__(self): return '\n'.join([str(c) for c in self.cards])
The Deck Class # deck.py # class to represent a deck of cards during a game of poker import random,sys from card import Card from poker_hand import Hand # List of cards as found when a new deck is opened. newDeckList = [] for s in ['c','d','h','s']: for r in range(1,14): newDeckList.append(Card(r,s))
The Deck Class # deck.py (continued) class Deck: def__init__(self,cardList=newDeckList):self.cardList = cardListself.top= 0 defopen_new_deck(self):self.cardList = newDeckListself.top= 0 defshuffleDeck(self):random.seed()random.shuffle(self.cardList)
The Deck Class # deck.py (continued) # class Deck, continued defdealHand(self): # cards removed from deck as they are dealt if len(self.cardList) < 5:return None self.top += 5 return Hand(self.cardList[self.top-5:self.top]) defcards_left(self): return 52-self.top defgenerateRandomHand(self): # cards not removed from Deck; no need to shuffle L = random.sample(self.cardList,5) return Hand(L)
The Deck Class # deck.py (continued) if __name__ == '__main__': mydeck = Deck() print('New deck has',mydeck.cards_left(), 'cards in the deck') print('Now shuffle the cards and deal a hand:') mydeck.shuffleDeck() myhand = mydeck.dealHand() print() print(myhand) print() print('That leaves',mydeck.cards_left(), 'cards in the deck') print()
The Deck Class # deck.py (continued) mydeck.open_new_deck() print('Opened a new deck of cards') print('Lets generate a random hand', 'without removing the cards') newhand = mydeck.generateRandomHand() print() print(newhand)
card_game_simulator from deck import Deck from poker_hand import Hand if __name__ == '__main__': player_names = ['Terry','Ed','Ralph','Bernie'] player_hands = {} for p in player_names: player_hands[p] = None d = Deck() d.shuffleDeck()
card_game_simulator from deck import Deck from poker_hand import Hand player_names= ['Terry','Ed','Ralph','Bernie'] player_hands= {} for p in player_names: player_hands[p] = None d = Deck() d.shuffleDeck() for p in player_names: player_hands[p] = d.dealHand() print(p,player_hands[p].poker_description()) print('\n')
card_game_simulator Freq= {} hand_values = ['Royal Flush','StraightFlush','Four of a Kind', 'Full House','Flush', 'Straight', 'Three of a Kind','TwoPair','Pair','HighCard' ] for t in hand_values: Freq[t] = 0 d = Deck() for i in range(100000): h = d.generateRandomHand() Freq[h.poker_description()] += 1 for t in hand_values: print(t,':',Freq[t])
Assignment 5: The Cards Project Out of 100,000 hands: