使用phrase_from_file读取文件的行
我一直在尝试使用 phrase_from_file
和语法规则解析包含整数行的文件
line --> I,line,{integer(I)}.
line --> ['\n'].
: phrase_from_file(line,'input.txt').
它失败了,并且我试图追踪它时很快就迷路了。 我什至尝试打印 I
,但它甚至没有到达那里。
编辑:: 由于下面的解决方案都不符合我的需求(使用 read/1
假设您正在阅读术语,有时编写 DCG 可能需要太长的时间),因此我拆解了 这段代码是我在谷歌上搜索的,主要变化是添加了:
read_rest(-1,[]):-!.
read_word(C,[],C) :- ( C=32 ;
C=(-1)
) , !.
I've been trying to parse a file containing lines of integers using phrase_from_file
with the grammar rules
line --> I,line,{integer(I)}.
line --> ['\n'].
thusly: phrase_from_file(line,'input.txt').
It fails, and I got lost very quickly trying to trace it.
I've even tried to print I
, but it doesn't even get there.
EDIT::
As none of the solutions below really fit my needs (using read/1
assumes you're reading terms, and sometimes writing that DCG might just take too long), I cannibalized this code I googled, the main changes being the addition of:
read_rest(-1,[]):-!.
read_word(C,[],C) :- ( C=32 ;
C=(-1)
) , !.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是
phrase_from_file/2
,有一种非常简单的方法可以在读取实际文件之前测试您的程序。只需使用phrase/2
调用相同的非终结符即可。 目标与调用相同
因此,当 fichier 是包含以上 3 个字符的文件时, 。因此,您可以使用
phrase/2
以非常紧凑的方式进行测试和实验。@Jan Burse 已经提到了更多问题。 SWI 读取字符代码。所以你必须写
一个换行符。然后你仍然需要自己解析整数。但使用
phrase/2
可以更轻松地测试所有这些。好处是您可以切换到读取文件而无需更改实际的 DCG 代码。If you are using
phrase_from_file/2
there is a very simple way to test your programs prior to reading actual files. Simply call the very same non-terminal withphrase/2
. Thus, a goalis the same as calling
when fichier is a file containing above 3 characters. So you can test and experiment in a very compact manner with
phrase/2
.There are further issues @Jan Burse already mentioned. SWI reads in character codes. So you have to write
for a newline. And then you still have to parse integers yourself. But all that is tested much easier with
phrase/2
. The nice thing is that you can then switch to reading files without changing the actual DCG code.我想这里有一个概念问题。虽然我不知道phrase_from_file/2的详细信息,即您正在使用哪个Prolog系统,但我仍然假设它会产生字符代码。因此,对于文件中的整数 123,您将得到字符代码 0'1、0'2 和 0'3。这可能不是您想要的。
如果您想处理字符,则需要使用非终端而不是简单的变量 I 来获取它们。您需要进行字符测试,而不是整数测试,并且您可以更早地进行测试:
最好的问候
P.S.:您也可以使用术语读取操作,而不是采用 DCG 方式。参见:
从 prolog 中的文件中读取数字并排序
I guess there is a conceptional problem here. Although I don't know the details of phrase_from_file/2, i.e. which Prolog system you are using, I nevertheless assume that it will produce character codes. So for an integer 123 in the file you will get the character codes 0'1, 0'2 and 0'3. This is probably not what you want.
If you would like to process the characters, you would need to use a non-terminal instead of a bare bone variable I, to fetch them. And instead of the integer test, you would need a character test, and you can do the test earlier:
Best Regards
P.S.: Instead of going the DCG way, you could also use term read operations. See also:
read numbers from file in prolog and sorting