1

我正在尝试使用 pyDatalog.load() 方法来加载一个小的 pyDatalog 程序。例如,我正在从https://sites.google.com/site/pydatalog/加载阶乘样本

from pyDatalog import pyDatalog
pyDatalog.create_atoms('factorial, N, F') # gives datalog capability to these words

def run_program():

    N = pyDatalog.Variable()
    F = pyDatalog.Variable()
    file_in = open("sample_datalog_program.dl", 'r')
    mc = file_in.read()
    print mc
    @pyDatalog.program()
    def _(): # the function name is ignored
        pyDatalog.load(mc)
        #pyDatalog.load("""
        #+ (factorial[1]==1)
        #(factorial[N] == F) <= (N > 1) & (F == N*factorial[N-1])
        #""")
        print(pyDatalog.ask('factorial[4]==F'))
    file_in.close()
    pass


if __name__ == "__main__":
    run_program()

文件 sample_datalog_program.dl 包含以下内容:

"""
+ (factorial[1]==1)
(factorial[N] == F) <= (N > 1) & (F == N*factorial[N-1])
"""

我究竟做错了什么?当我用接下来的 4 条注释行替换 pyDatalog.load(mc) 行时,它工作正常。

我得到的错误是:

    /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/bin/python2.7    run_datalog_program.py
pyDatalog version 0.12.0
Traceback (most recent call last):
  File "run_datalog_program.py", line 25, in <module>
    run_program()
  File "run_datalog_program.py", line 11, in run_program
    @pyDatalog.program()
  File "/usr/local/lib/python2.7/site-packages/pyDatalog/pyParser.py", line 191, in   add_program
    load(source_code, newglobals, defined, function=func_name)
  File "/usr/local/lib/python2.7/site-packages/pyDatalog/pyParser.py", line 154, in load
six.exec_(code, newglobals)
  File "/usr/local/lib/python2.7/site-packages/six.py", line 308, in exec_
    exec("""exec code in globs, locs""")
  File "<string>", line 1, in <module>
  File "_", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pyDatalog/pyDatalog.py", line 115, in load
    return pyParser.load(code)
  File "/usr/local/lib/python2.7/site-packages/pyDatalog/pyParser.py", line 133, in load
    spaces = r.match(line).group()
TypeError: expected string or buffer
"""
+ (factorial[1]==1)
(factorial[N] == F) <= (N > 1) & (F == N*factorial[N-1])
"""

Process finished with exit code 1

谢谢!

4

1 回答 1

0

您不应混合使用 pyDatalog.load() API 和内联 API。请参阅动态数据记录语句(在页面底部)

以下是编写程序的方法:

from pyDatalog import pyDatalog

def run_program():

    file_in = open("sample_datalog_program.dl", 'r')
    mc = file_in.read()
    print mc
    pyDatalog.load(mc)
    file_in.close()
    print(pyDatalog.ask('factorial[3]==N'))

if __name__ == "__main__":
    run_program()

sample_datalog_program.dl 中的代码应该是(不带三引号):

+ (factorial[1]==1)
(factorial[N] == F) <= (N > 1) & (F == N*factorial[N-1])
于 2013-02-06T19:00:32.103 回答