我想使用 python 从文件中检索随机单词,但我不相信我的以下方法是最好或有效的。请协助。
import fileinput
import _random
file = [line for line in fileinput.input("/etc/dictionaries-common/words")]
rand = _random.Random()
print file[int(rand.random() * len(file))],
random 模块定义了 choice(),它可以完成您想要的操作:
import random
words = [line.strip() for line in open('/etc/dictionaries-common/words')]
print(random.choice(words))
另请注意,这假设每个单词单独位于文件中的一行上。如果文件非常大,或者频繁执行此操作,您可能会发现不断重新读取文件会对应用程序的性能产生负面影响。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)