Hi,

I need some help on how to read a file

2 h
3 s
6 d
Ace s
...

Importing this into Python and then sorting and printing in order.

I have done some work, yet I can never seem to get the data to Python and split it accordingly>
Class Card:
def __init__(self, rank, suit):
'''Indicates rank from 1-13, as well as the card's 4 different suits'''
self.rank = rank
self.suit = suit
self.ranks = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
self.suits = ["Spades","Diamonds","clubs","hearts"]
self.BJ = [None, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

How do I split the file into the two pieces ie 2 h to equal 2 and Hearts.

macca1111

Here is one way to do it, using slicing, a for loop and indexing with enumerate():

# let's say you read your file in as a string ...
str1 = """
2 h
3 s
6 d
Ace s
"""

list1 = str1.split()

print list1  # ['2', 'h', '3', 's', '6', 'd', 'Ace', 's']

suit_list = list1[1::2]
rank_list = list1[0::2]

print suit_list  # ['h', 's', 'd', 's']
print rank_list  # ['2', '3', '6', 'Ace']

# replace h with Hearts etc.
for index, suit in enumerate(suit_list):
    if suit == 'h':
        suit_list[index] = "Hearts"
    elif suit == 'c':
        suit_list[index] = "Clubs"
    elif suit == 's':
        suit_list[index] = "Spades"
    elif suit == 'd':
        suit_list[index] = "Diamonds"

print suit_list  # ['Hearts', 'Spades', 'Diamonds', 'Spades']

Please use code tags on your code to preserve the all so important indentation!!!!!!!!!!!

Hi, thks for your help Ene...

I have the following code that does sort of works.

I'm not quite sure how to get the shuffle working and selecting a card from the top and removing it.

import string

list1 = open('H:\cards.txt').read()

class Card:
    suitList = list1[1::2]
    rankList = list1[0::2]
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        
    def __repr__(self):
        return str(self)
    
    def __str__(self):
        return "%s of %s" % (self.rankList[self.rank],self.suitList[self.suit])
    
    def __cmp__(self,other):
        if self.suit > other.suit: return 1
        if self.suit < other.suit: return -1
        if self.rank > other.rank: return 1
        if self.rank < other.rank: return -1
        return 0

class Deck:
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1,14):
                self.cards.append(Card(suit,rank))

    def printDeck(self):
        for card in self.cards:
            print card
                
    def __str__(self):
      s = ""
      for i in range(len(self.cards)):
        s = s + " " + str(self.cards[i]) + "\n"
      return s #= s + " " + str(self.cards[i]) + '\n'

    def shuffle(self):
        import random
        nCards = len(self.cards)
        for i in range(nCards):
            j = random.randrange(i, nCards)
            [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]]

    def removeCard(self, card):
        if card in self.cards:
          self.cards.remove(card)
          return 1
        else: return 0
        
    def popCard(self):
        return self.cards.pop()
    
def main():
    list2 = list1.split()
    Card.suitList = list2[1::2]
    Card.rankList = list2[0::2]
    deck = Deck()
    deck.shuffle()    ###How can I have this now shuffled deck        saved to cards.txt
    
    
    print Card.suitList
    print Card.rankList

    # replace suit with full word
    for index, suit in enumerate(Card.suitList):
        if suit == 'h':
            Card.suitList[index] = "Hearts"
        elif suit == 'c':
            Card.suitList[index] = "Clubs"
        elif suit == 's':
            Card.suitList[index] = "Spades"
        elif suit == 'd':
            Card.suitList[index] = "Diamonds"


    
    
main()

regards
macca111

Edit: Be polite to the people willing to help you! Please add code tags around your code!
See: http://www.daniweb.com/techtalkforums/announcement114-3.html

Just a note, function names like __str__, __repr__, __cmp__ have a special meaning in Python, do not use them for your class methods unless you want them to fullfill this special purpose.

Hi,

I seem to be going around in circles. Probably not knowing much about Python doens't help.

With the following code I need to get it to:
1. read a file in then shuffle the pack and save it to the same file.

2 h
3 d
5 d
...

2. read the file then sort it, then print out n number of cards
3. have the top card removed
4. print out the number of cards

import string

list1 = open('H:\cards.txt').read()

class Card:
    suitList = list1[1::2]
    rankList = list1[0::2]
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        
    def __repr__(self):
        return str(self)
    
    def __str__(self):
        return "%s of %s" % (self.rankList[self.rank],self.suitList[self.suit])
    
    def __cmp__(self,other):
       if self.suit > other.suit: return 1
       if self.suit < other.suit: return -1
       if self.rank > other.rank: return 1
       if self.rank < other.rank: return -1
       return 0

class Deck:
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1,14):
                self.cards.append(Card(suit,rank))

    def printDeck(self):
        for card in self.cards:
            print card
                
    def __str__(self):
      s = ""
      for i in range(len(self.cards)):
        s = s + " " + str(self.cards[i]) + "\n"
      return s #= s + " " + str(self.cards[i]) + '\n'

    def shuffle(self):
        import random
        nCards = len(self.cards)
        # Swap randomly selected card i with randomly selected card j
        for i in range(nCards):
            j = random.randrange(i, nCards)
            [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]]

    def removeCard(self, card):
        if card in self.cards:
          self.cards.remove(card)
          return 1
        else: return 0
        
    def popCard(self):
        return self.cards.pop()
    
def main():
    list2 = list1.split()
    Card.suitList = list2[1::2]
    Card.rankList = list2[0::2]
    deck = Deck()
    deck.shuffle()
   
    # replace suit with full word
    for index, suit in enumerate(Card.suitList):
        if suit == 'h':
            Card.suitList[index] = "Hearts"
        elif suit == 'c':
            Card.suitList[index] = "Clubs"
        elif suit == 's':
            Card.suitList[index] = "Spades"
        elif suit == 'd':
            Card.suitList[index] = "Diamonds"

    print deck

    
    
main()

I think you should change your code to use inheritance and a tuple for the cards (that someone else mentioned at one point). It seems like this code is more complex than it needs to be. That's just my opinion.

Here is one way to do it, using slicing, a for loop and indexing with enumerate():

# let's say you read your file in as a string ...
str1 = """
2 h
3 s
6 d
Ace s
"""

list1 = str1.split()

print list1  # ['2', 'h', '3', 's', '6', 'd', 'Ace', 's']

suit_list = list1[1::2]
rank_list = list1[0::2]

print suit_list  # ['h', 's', 'd', 's']
print rank_list  # ['2', '3', '6', 'Ace']

# replace h with Hearts etc.
for index, suit in enumerate(suit_list):
    if suit == 'h':
        suit_list[index] = "Hearts"
    elif suit == 'c':
        suit_list[index] = "Clubs"
    elif suit == 's':
        suit_list[index] = "Spades"
    elif suit == 'd':
        suit_list[index] = "Diamonds"

print suit_list  # ['Hearts', 'Spades', 'Diamonds', 'Spades']

Please use code tags on your code to preserve the all so important indentation!!!!!!!!!!!

Hi,

I have the following code yet it doesn't replace anything other than the hearts:

import string

f = open('C:\cs.txt','r').read()

class Card:
    suitList = f[1::2]
    rankList = f[0::2]
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        
    def __repr__(self):
        return str(self)
    
    def __str__(self):
        return "%s of %s" % (self.rankList[self.rank],self.suitList[self.suit])
    
    def __cmp__(self,other):
       if self.suit > other.suit: return 1
       if self.suit < other.suit: return -1
       if self.rank > other.rank: return 1
       if self.rank < other.rank: return -1
       return 0

class Deck:
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1,14):
                self.cards.append(Card(suit,rank))

    def printDeck(self):
        for card in self.cards:
            print card

    def __str__(self):
        s = ""
        for i in range(len(self.cards)):
            s = s + " " + str(self.cards[i]) + '\n'
        return s


def main():
    cardList = f.split()
    Card.suitList = cardList[1::2]
    Card.rankList = cardList[0::2]

    # replace suit with full word
    for index, suit in enumerate(Card.suitList):
        if suit == 'h':
            Card.suitList[index] = "Hearts"
        elif suit == 'c':
            Card.suitList[index] = "Clubs"
        elif suit == 's':
            Card.suitList[index] = "Spades"
        elif suit == 'd':
            Card.suitList[index] = "Diamonds"

    print Deck()
    
       

main()

My cs.txt file is

Ace h
2 h
3 h
...
2 d
3 d
...

and the output is all ... of hearts.

2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts
2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts

I'm not too sure why it replaces the 'hearts' yet not anything else.

This question has already been answered. Start a new discussion instead.