views:

86

answers:

3

how can i using random function (in python) to choice a string from a txt list ? thanks a lot

+2  A: 
> import random
> list_of_strings = open(sys.argv[1]).readlines()
> randomly_chosen_string = random.choice(list_of_strings)
> help(random.choice)
Help on method choice in module random:

choice(self, seq) method of random.Random instance
Choose a random element from a non-empty sequence.
Stephen
A: 

i want random from a list :

import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print  random.choice(f)

is this code ok ?

Emma
Not exactly. Did you try it? You should edit your question to add more detail, instead of posting an answer. I've edited my answer to read from the file. Also, you might give more details on the format of the file.
Stephen
`f.close` needs to be `f.close()`. Your code will select a random character from the file. What is the result you want? You should put more detail in the question.
None
+1  A: 
import random

file = open("file.txt", "r")
list = file.readlines()
def getline ():
    return list[random.randint(0,(len(list) - 1))]

getline()
krzysz00
assuming that file.txt contains sonething likeaaabbbcccetc...(one word per line)then that will work
krzysz00
+1 for brevity, and welcome to SO! But please don't use `list` for a variable name, as `list()` is a function name in Python. Also, you should look into the `with` statements for file reading. :]
Xavier Ho
sorry, don't know much Python and this was the first thing to come into my head and BTW, I figured common lisp doesn't choke on there being a variable AND a function named list, so why should Python
krzysz00