mercredi 6 mai 2015

Reading only str objects from a file

So while working on my program I'm trying to read a file, bring back all the information contained. While another function splits the list and random generates a string contained. If it's not a string, try again.

Unfortunally my program flips out while doing this and completely refuses to obey or just gives me an error or yeah, flips out.

So now I'm looking for a way to only read the string objects so I can skip the whole part where it checks if it's an integer or not.

import random
from random import randrange
def readfile(file):
    try:
        f = open(file, 'r')
        fil = f.readlines()
        f.close()
        return fil
    except IOError:
        print('fil finns inte')
        return None

def chooseword(lista):
    while True:
        lista = random.choice(lista)
        ordet = lista.split()
        x = randrange(len(ordet))
        ord = ordet[x]
        try:
            if ord.isalpha:
                return ord
        except:
            print("none")

print(chooseword(readfile("file.txt")))

I've tried with working with random.choice instead of randrange which made no difference.

So, how would I go forward to only import string objects like words, ex: Banan and not 123 or ¤%&.

Thanks

Thanks




Aucun commentaire:

Enregistrer un commentaire