我已经编写了下面的Python代码,并试图通过从python shell导入它作为模块,但它的抛出错误。
def break_words(stuff):
"""This function will break up words fro us."""
words = stuff.split('')
return words
def sort_words(words):
"""sort the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word=words.pop(0)
print word
def print_last_word(words):
"""print the last word after poppomg it off."""
word=words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes a full sentence and return the sorted word."""
words= break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last word of the sentences."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
当我从python shell导入它时: -
>>> import Breaking_code
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import Breaking_code
ImportError: No module named Breaking_code
我的目标是将其用作下面的模块
sentence = "All good things come to those who wait."
words = Breaking_code.break_words(sentence)
output:- ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
答案 0 :(得分:1)
确定您已在某个目录中编写了一个要在shell中导入的模块。但是模块的范围仅限于模块所在的目录。要在shell中导入模块
有两个选项
1.在系统环境变量中添加模块所在的目录。您也可以通过代码执行此操作
import sys
sys.path.append("your\\ directory\\path here")
import breaking_code
2.只需快速更改目录
import os
os.chdir("your\\ directory\\path here") #changing current working directory
import breaking_code
答案 1 :(得分:-1)
Breaking_Code.py很可能不在Python shell所在的文件夹中。如果只是尝试使用
导入一个函数来自breaking_code import sort_words