Python 3 的导入错误

ImportError with Python 3

我正在尝试 运行 来自 ThinkStats2 代码的示例。我从 github 复制了所有内容 - 文件结构与 github.

上给出的完全相同
chap01soln.py

from __future__ import print_function

import numpy as np
import sys

import nsfg
import thinkstats2


def ReadFemResp(dct_file='2002FemResp.dct',
                dat_file='2002FemResp.dat.gz',
                nrows=None):
    """Reads the NSFG respondent data.

    dct_file: string file name
    dat_file: string file name

    returns: DataFrame
    """
    dct = thinkstats2.ReadStataDct(dct_file)
    df = dct.ReadFixedWidth(dat_file, compression='gzip', nrows=nrows)
    CleanFemResp(df)
    return df


def CleanFemResp(df):
    """Recodes variables from the respondent frame.

    df: DataFrame
    """
    pass


def ValidatePregnum(resp):
    """Validate pregnum in the respondent file.

    resp: respondent DataFrame
    """
    # read the pregnancy frame
    preg = nsfg.ReadFemPreg()

    # make the map from caseid to list of pregnancy indices
    preg_map = nsfg.MakePregMap(preg)

    # iterate through the respondent pregnum series
    for index, pregnum in resp.pregnum.iteritems():
        caseid = resp.caseid[index]
        indices = preg_map[caseid]

        # check that pregnum from the respondent file equals
        # the number of records in the pregnancy file
        if len(indices) != pregnum:
            print(caseid, len(indices), pregnum)
            return False

    return True


def main(script):
    """Tests the functions in this module.

    script: string script name
    """
    resp = ReadFemResp()

    assert(len(resp) == 7643)
    assert(resp.pregnum.value_counts()[1] == 1267)
    assert(ValidatePregnum(resp))

    print('%s: All tests passed.' % script)


if __name__ == '__main__':
    main(*sys.argv)

我收到如下所示的 ImportError:

Traceback (most recent call last):
  File "C:\wamp\www\ThinkStats_py3\chap01soln.py", line 13, in <module>
    import nsfg
  File "C:\wamp\www\ThinkStats_py3\nsfg.py", line 14, in <module>
    import thinkstats2
  File "C:\wamp\www\ThinkStats_py3\thinkstats2.py", line 34, in <module>
    import thinkplot
  File "C:\wamp\www\ThinkStats_py3\thinkplot.py", line 11, in <module>
    import matplotlib
  File "C:\Python34\lib\site-packages\matplotlib\__init__.py", line 105, in <module>
    import six
ImportError: No module named 'six'

所有文件都列在 src 文件夹下。 src 下没有包。我尝试为 nsfg 和 thinkstats 添加包,但出现了另一个错误。我尝试将 python 2.7 升级到 python 3.4。我仍然遇到同样的错误。我知道我需要为 matplotlib 安装六个包,但为什么我在 nsfg 上出现导入错误?

您在 nsfg 上收到导入错误,因为它在内部导入 matplotlib(不是直接导入,而是 imports thinkstats2 导入 thinkplot 导入 matplotlib ,依赖于 six 模块)。并且您的计算机上没有安装该库,因此导入失败。

很可能您没有 six 模块,您可以尝试使用 - pip install six .

安装它

或从 here 获取,解压缩并使用 - python setup.py install

安装