简体   繁体   English

Prolog:删除字符流中的额外空格

[英]Prolog : Remove extra spaces in a stream of characters

Total newb to Prolog. 总计新闻到Prolog。 This one is frustrating me a bit. 这个让我感到沮丧。 My 'solution' below is me trying to make Prolog procedural... 下面我的“解决方案”是我试图让Prolog程序化......

This will remove spaces or insert a space after a comma if needed, that is, until a period is encountered: 如果需要,这将删除空格或在逗号后插入空格,即直到遇到句点:

squish:-get0(C),put(C),rest(C).  
rest(46):-!.  
rest(32):-get(C),put(C),rest(C).  
rest(44):-put(32), get(C), put(C), rest(C).  
rest(Letter):-squish. 

GOAL: I'm wondering how to remove any whitespace BEFORE the comma as well. 目标:我想知道如何在逗号之前删除任何空格。

The following works, but it is so wrong on so many levels, especially the 'exit'! 以下是有效的,但在很多层面都是如此错误,特别是'退出'!

squish:-  
  get0(C),  
  get0(D),  
  iteratesquish(C,D).  

iteratesquish(C,D):-  
  squishing(C,D),  
  get0(E),  
  iteratesquish(D,E).  

squishing(46,X):-put(46),write('end.'),!,exit.  

squishing(32,32):-!.  
squishing(32,44):-!.  
squishing(32,X):-put(32),!.   

squishing(44,32):-put(44),!.  
squishing(44,44):-put(44), put(32),!.  
squishing(44,46):-put(44), put(32),!.  
squishing(44,X):-put(44), put(32),!.  

squishing(X,32):-put(X),!.  
squishing(X,44):-put(X),!.  
squishing(X,46):-put(X),!.  

squishing(X,Y):-put(X),!.  

Since you are describing lists (in this case: of character codes), consider using DCG notation. 由于您正在描述列表(在本例中为:字符代码),请考虑使用DCG表示法。 For example, to let any comma be followed by a single whitespace, consider using code similar to: 例如,要让任何逗号后跟单个空格,请考虑使用类似于以下内容的代码:

squish([])                 --> [].
squish([(0',),(0' )|Rest]) --> [0',], spaces, !, squish(Rest).
squish([L|Ls])             --> [L], squish(Ls).

spaces --> [0' ], spaces.
spaces --> [].

Example query: 示例查询:

?- phrase(squish(Ls), "a,   b,c"), format("~s", [Ls]).
a, b, c

So, first focus on a clear declarative description of the relation between character sequences and the desired "clean" string. 因此,首先关注字符序列与所需“干净”字符串之间关系的清晰声明性描述。 You can then use SWI-Prolog's library(pio) to read from files via these grammar rules. 然后,您可以使用SWI-Prolog的库(pio)通过这些语法规则从文件中读取。 To remove all spaces preceding commas, you only have to add a single rule to the DCG above (to squish//1), which I leave as exercise to you. 要删除逗号之前的所有空格,您只需要向上面的DCG添加一个规则(以挤压// 1),我将其作为练习留给您。 A corner case of course is if a comma is followed by another comma, in which case the requirements are contradictory :-) 一个角落的情况当然是如果一个逗号后跟另一个逗号,在这种情况下要求是矛盾的:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM