如何使用隨機函數(在Python中)從txt列表中選擇一個字符串?Python中的隨機函數
我想隨機從列表:
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
是這段代碼好嗎?
如何使用隨機函數(在Python中)從txt列表中選擇一個字符串?Python中的隨機函數
我想隨機從列表:
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
是這段代碼好嗎?
> 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.
import random
file = open("file.txt", "r")
list = file.readlines()
def getline():
return list[random.randint(0,(len(list) - 1))]
getline()
假設file.txt的包含sonething像 AAA BBB CCC 等等 (每行一個字) 然後,將工作 – krzysz00 2010-05-22 11:42:04
+1爲了簡潔,歡迎SO!但是請不要使用'list'作爲變量名,因爲'list()'是Python中的一個函數名。另外,您應該查看'with'語句來讀取文件。 :] – 2010-05-22 12:34:54
對不起,不瞭解太多的Python,這是第一個進入我的腦海和順便說一句,我認爲普通的lisp不會扼殺有變量和名爲list的函數,那麼爲什麼Python – krzysz00 2010-05-22 14:01:33
選擇聽起來是正確的。 – Stephen 2010-05-22 02:29:39
至少在提問前假裝看看非常非常好的文檔...... – 2010-05-22 02:31:24
您可以編輯標題或擴展您的問題。正如所寫,沒有提到隨機函數本身的任何具體問題。 – bernie 2010-05-22 02:41:47