[英]How to use a python function from another module
我尝试导入一个模块,并在我当前的python文件中使用该模块中的函数。
我在parser_tests.py文件上运行nosetests,但它失败了,“name'sparse_subject'未定义”
例如,它找不到在parsrer.py文件中明确定义的parse_subject函数
这是解析器文件:
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
#Confirms that the expected word is the right type,
def match(word_list,expecting):if word_list:word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list,word_type):while peek(word_list)== word_type:match(word_list,word_type)
def parse_verb(word_list):skip(word_list,'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):skip(word_list,'stop')next_word = peek(word_list)
if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_subject(word_list):skip(word_list,'stop')next_word = peek(word_list)
if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
def parse_sentence(word_list):subj = parse_subject(word_list)verb = parse_verb(word_list)obj = parse_object(word_list)
return Sentence(subj, verb, obj)
这是我的测试文件
from nose.tools import *
来自nose.tools import assert_equals import sys sys.path.append(“h:/ projects / projectx48 / ex48”)
导入解析器
def test_subject():word_list = [('noun','bear'),('verb','eat'),('stop','the'),('noun','honey')] assert_equals( parse_subject(word_list),('noun','bear'))
您可以导入整个模块,也可以使用示例关键字专门导入该特定函数。
例如:
from parser_tests import parse_subject
# and then you can invoke the function.
parse_subject()
如果没有看到您的代码,很难确切地知道如何诊断您的问题,但这是我最好的猜测,可能会有什么帮助。
首先, parser
已经是Python中的内置模块,因此您应该为parser.py文件考虑不同的名称。
其次,您应该确保可以在sys.path
找到parser.py文件所在目录的路径。 您可以通过从当前Python文件运行此代码段来自行检查:
import sys
for line in sys.path:
print line
如果找到parser.py
的目录未包含在您的path
,则可以将该路径附加到sys.path
,如下所示:
import sys
sys.path.append("/path/to/your/module")
最后,您应该确保在当前的Python文件中正确导入函数,如下所示:
from parser import parser_subject
可能是已经存在一个称为解析器的内置函数。 我正在调用我在本地创建的一个parser.py文件,而不是我放在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.