python writefile ImportError:没有名为“mainss\u script”的模块

2024-09-28 05:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

%%writefile mainss_script.py
def count_vowels(sentence):
    """Count the number of vowels in sentence."""
    vowels = 0
    for c in sentence:
        if c.lower() in "aeiouy":
            vowels = vowels + 1
    return vowels

def count_consonants(sentence):
    """Count the number of consonants in sentence."""
    consonants = 0
    for c in sentence:
        if c.isalpha():
            if c.lower() not in "aeiouy":
                consonants = consonants + 1
    return consonants

def count_digits(sentence):
    """Count the number of digits in sentence."""
    digits = 0
    for c in sentence:
        if c.isdigit():
            digits = digits + 1
    return digits
def mainss():
    test_sentence = "Plan 2 is not working!"
    print("Number of vowels = {:d}".format(count_vowels(test_sentence)))
    print("Number of consonants = {:d}".format(count_consonants(test_sentence)))
    print("Number of digits = {:d}".format(count_digits(test_sentence)))

if (__name__=="__main__"):
    mainss()

import mainss_script
mainss_script.mainss()

ImportError                               Traceback (most recent call last)
<ipython-input-66-1fd7edecdd49> in <module>()
----> 1 import mainss_script
      2 mainss_script.mainss()

ImportError: No module named 'mainss_script'

缅因州_脚本.py但是,当我试图导入它时,它返回错误,为什么??你知道吗

忽略for word要求忽略for word要求忽略for word要求


Tags: oftheintestforifdefcount
1条回答
网友
1楼 · 发布于 2024-09-28 05:21:02

文件mains_脚本.py必须在启动ipython的目录中。你知道吗

如果没有,您可以将其位置插入sys.path,以便解释器找到它

import sys
sys.path.insert(0, "path to mainss_script.py")

import mainss_script
mainss_script.mainss()

另外,%%writefile是将单元格内容写入文件的Jupyter magic alias命令。所以我猜你的代码是从某个Jupyter笔记本上复制过来的,运行包含这些行的单元格会在当前目录中创建mainss_script。你知道吗

如果没有该文件,请将那些代码行(不包括%%writefile行)粘贴到文件mains中_脚本.py在启动IPython的同一目录中。你知道吗

如果出于某种原因您确实希望保存维护_脚本.py在特定位置,然后您应该按照上面的说明将mainss\u脚本的路径添加到sys.path中,以便解释器找到它。在那之后,执行要导入并运行mainss()的行,事情就应该正常了。你知道吗

相关问题 更多 >

    热门问题