python随机列表文本_从python中的单词列表中返回一个随机单词

用于比较的代码(as a gist): h3>

import linecache

import random

from timeit import default_timer

WORDS_FILENAME = "/etc/dictionaries-common/words"

def measure(func):

measure.func_to_measure.append(func)

return func

measure.func_to_measure = []

@measure

def dcrosta():

words = [line.strip() for line in open(WORDS_FILENAME)]

return random.choice(words)

@measure

def dcrosta_no_strip():

words = [line for line in open(WORDS_FILENAME)]

return random.choice(words)

def select_random_line(filename):

selection = None

count = 0

for line in file(filename, "r"):

if random.randint(0, count) == 0:

selection = line.strip()

count = count + 1

return selection

@measure

def mark_ransom():

return select_random_line(WORDS_FILENAME)

def select_random_line_no_strip(filename):

selection = None

count = 0

for line in file(filename, "r"):

if random.randint(0, count) == 0:

selection = line

count = count + 1

return selection

@measure

def mark_ransom_no_strip():

return select_random_line_no_strip(WORDS_FILENAME)

def choose_from(iterable):

"""Choose a random element from a finite `iterable`.

If `iterable` is a sequence then use `random.choice()` for efficiency.

Return tuple (random element, total number of elements)

"""

selection, i = None, None

for i, item in enumerate(iterable):

if random.randint(0, i) == 0:

selection = item

return selection, (i+1 if i is not None else 0)

@measure

def mark_ransom_choose_from():

return choose_from(open(WORDS_FILENAME))

@measure

def nadia():

global total_num_lines

total_num_lines = sum(1 for _ in open(WORDS_FILENAME))

line_number = random.randint(0, total_num_lines)

return linecache.getline(WORDS_FILENAME, line_number)

@measure

def nadia_known_num_lines():

line_number = random.randint(0, total_num_lines)

return linecache.getline(WORDS_FILENAME, line_number)

@measure

def jfs():

return random.choice(list(open(WORDS_FILENAME)))

def timef(func, number=1000, timer=default_timer):

"""Return number of seconds it takes to execute `func()`."""

start = timer()

for _ in range(number):

func()

return (timer() - start)/number

def main():

# measure time

times = dict((f.__name__, timef(f, number=10))

for f in measure.func_to_measure)

# print from fastest to slowest

maxname_len = max(map(len, times))

last = None

for name in sorted(times, key=times.__getitem__):

print "%s %4.2g seconds %.2f" % (name.ljust(maxname_len), times[name],

last and times[name]/last or 1)

last = times[name]

if __name__ == "__main__":

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值