AttributeError:'模块'对象没有属性' choice'

时间:2015-04-12 09:28:31

标签: python python-3.x random

我正在使用python3。 首先我在终端中使用random.choice,它可以工作。

Python 3.2.3 (default, Feb 27 2014, 21:31:18) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> x = [1, 2, 3]
>>> random.choice(x)
3

但是当我在我的脚本中运行它时,我收到了消息:

AttributeError: 'module' object has no attribute 'choice'

这是代码

import random
from scipy import *
from numpy import linalg as LA
import pickle
import operator


def new_pagerank_step(current_page, N, d, links):
    print(links[current_page])
    if random.rand() > 1 - d:
        next_page = random.choice(links[current_page])
    else:
        next_page = random.randint(0, N)
    return next_page


def pagerank_wikipedia_demo():
    with open("wikilinks.pickle", "rb") as f:
        titles, links = pickle.load(f)
    current_page = 0
    T = 1000
    N = len(titles)
    d = 0.4
    Result = {}
    result = []
    for i in range(T):
        result.append(current_page)
        current_page = new_pagerank_step(current_page, N, d, links)
    for i in range(N):
        result.count(i)
        Result[i] = result.count(i) / T
    Sorted_Result = sorted(Result.items(), key=operator.itemgetter(1))

pagerank_wikipedia_demo()

这里,links[i]i是一个整数)是一个列表。当我运行此脚本时,它失败并显示上述消息。

我还检查过脚本的名称不是randomrandom.py

中只有一个名为/usr/lib/python3.2/random.py的文件

为什么会这样?

2 个答案:

答案 0 :(得分:3)

您在此处使用numpy.random对象屏蔽了模块:

import random
from scipy import *

from scipy import *导入带来全部名称,包括random

>>> from scipy import *
>>> random
<module 'numpy.random' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/numpy/random/__init__.pyc'>

替换随机模块。

要么不使用通配符导入,要么在从random导入所有内容后导入scipy模块

您还可以从choice模块导入random并直接引用它,或使用其他名称将导入绑定到:

from random import choice
from scipy import *

# use choice, not random.choice

import random as stdlib_random
from scipy import *

# use stdlib_random.choice, not random.choice

答案 1 :(得分:1)

除了Martijin Pieters的回答,我想补充一点,您还可以使用别名导入random模块:

import random as rdm
from scipy import *       

# Then you can 
rdm.choice(some_sequence)