【发布时间】:2018-03-16 01:25:34
【问题描述】:
如何传递字符串并将其转换为 sml 中的单词列表?
例如:"one two three" 到 ["one", "two", "three"]
【问题讨论】:
-
您可以使用空格“”来分割字符串。这个例子非常相似,但需要一点tweeking。 stackoverflow.com/questions/43289155/…
如何传递字符串并将其转换为 sml 中的单词列表?
例如:"one two three" 到 ["one", "two", "three"]
【问题讨论】:
您可以(并且可能应该)使用String.tokens:
- String.tokens Char.isSpace "one two three";
> val it = ["one", "two", "three"] : string list
还有String.fields。它们在处理连续/多余分隔符的方式上有所不同:
- String.tokens Char.isSpace " one two three ";
> val it = ["one", "two", "three"] : string list
- String.fields Char.isSpace " one two three ";
> val it = ["", "", "one", "", "two", "", "three", "", ""] : string list
如果您的字符串有多个潜在的分隔符并且您只对单词感兴趣:
fun isWordSep c = Char.isSpace c orelse
( Char.isPunct c andalso c <> #"-" andalso c <> #"'" )
val words = String.tokens isWordSep
这适用于单词是什么的一种定义:
- words "I'm jolly-good. Are you?";
> val it = ["I'm", "jolly-good", "Are", "you"] : string list
并非所有自然语言都会遵守此定义,例如e.g. 是一个首字母缩写词,而不是两个词,e 和 g。对于任何准确性,您都将进入自然语言处理领域。
【讨论】: