AttributeError的:“模块”对象有没有属性“选择”(AttributeError: &#

2019-10-22 14:58发布

我使用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是整数)是一个列表。 当我运行此脚本时,出现上述消息。

我还检查了脚本的名称不是random 。 并且只有一个名为文件random.py/usr/lib/python3.2/random.py

为什么出现这种情况?

Answer 1:

您屏蔽与模块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

您也可以导入choicerandom模块,并直接引用它,或者绑定到进口使用不同的名称:

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


Answer 2:

除了Martijin Pieters的答案,我想补充一点,你也可以导入random模块与一个别名:

import random as rdm
from scipy import *       

# Then you can 
rdm.choice(some_sequence)


文章来源: AttributeError: 'module' object has no attribute 'choice'