1 / 23

A Censor Class

A Censor Class. class Censor : def __ init __ ( self,replacers ='!@$%&?', badwords =[]): self.badwords = badwords self.replacers = replacers

filia
Download Presentation

A Censor Class

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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()

  2. 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)

  3. 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

  4. 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)

  5. 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

  6. The Card Class # Card class definition continued defBJValue(self): # Blackjack card valueif self.rank <= 10:return self.rankelse:return 10

  7. 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 '

  8. 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

  9. 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

  10. 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]

  11. 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

  12. 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

  13. 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"

  14. 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])

  15. 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))

  16. 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)

  17. 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)

  18. 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()

  19. 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)

  20. 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()

  21. 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')

  22. 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])

  23. Assignment 5: The Cards Project Out of 100,000 hands:

More Related