Engee 文档
Notebook

过滤控制ASCII字符

简要资料

此示例演示使用内置函数从一系列字符中筛选控制ASCII字符 filter 和谓词 iscntrl.

导言

ASCII控制字符是ASCII表中的特殊字符,代码从0到31和127,不是可视显示的,而是执行用于控制输入/输出设备,格式化文本和传输数据的特殊功能。 它们用于控制终端、打印机和其他设备的行为。 例如,符号 \n (带代码10)用于翻译字符串,字符 \t (代码9)-用于制表。 在编程中,经常需要判断一个字符是否是控制字符,或者从文本中过滤这样的字符。 Julia语言为此提供了内置函数,包括 iscntrl 检查字符是否为控制字符,以及 filter 允许您选择满足指定条件的集合项。

主要部分

准备字符范围

创建从0到127的所有ASCII字符的范围

Char(0) -代码为0的符号(\0)

Char(127) -带有代码127的符号(\x7f)

In [ ]:
chars_range = Char(0):Char(127)
Out[0]:
'\0':1:'\x7f'

在这里,我们从代码为0(零字符)的字符中创建一个字符范围, '\0')至127个字符('\x7f'),复盖整个ASCII表。 Julia语言中的范围允许您处理元素序列,其中每个元素都遵循前一个元素并具有特定步骤。 在这种情况下,默认步骤为1,因此我们得到所有128个ASCII字符。

过滤控制字符

我们应用过滤器只选择控制字符。:

  • iscntrl -检查字符是否为控制字符的函数

  • filter 将谓词应用于范围的每个元素,并仅返回谓词返回true的那些元素的数组。

In [ ]:
control_chars = filter(iscntrl, chars_range)
Out[0]:
33-element Vector{Char}:
 '\0': ASCII/Unicode U+0000 (category Cc: Other, control)
 '\x01': ASCII/Unicode U+0001 (category Cc: Other, control)
 '\x02': ASCII/Unicode U+0002 (category Cc: Other, control)
 '\x03': ASCII/Unicode U+0003 (category Cc: Other, control)
 '\x04': ASCII/Unicode U+0004 (category Cc: Other, control)
 '\x05': ASCII/Unicode U+0005 (category Cc: Other, control)
 '\x06': ASCII/Unicode U+0006 (category Cc: Other, control)
 '\a': ASCII/Unicode U+0007 (category Cc: Other, control)
 '\b': ASCII/Unicode U+0008 (category Cc: Other, control)
 '\t': ASCII/Unicode U+0009 (category Cc: Other, control)
 '\n': ASCII/Unicode U+000A (category Cc: Other, control)
 '\v': ASCII/Unicode U+000B (category Cc: Other, control)
 '\f': ASCII/Unicode U+000C (category Cc: Other, control)
 ⋮
 '\x15': ASCII/Unicode U+0015 (category Cc: Other, control)
 '\x16': ASCII/Unicode U+0016 (category Cc: Other, control)
 '\x17': ASCII/Unicode U+0017 (category Cc: Other, control)
 '\x18': ASCII/Unicode U+0018 (category Cc: Other, control)
 '\x19': ASCII/Unicode U+0019 (category Cc: Other, control)
 '\x1a': ASCII/Unicode U+001A (category Cc: Other, control)
 '\e': ASCII/Unicode U+001B (category Cc: Other, control)
 '\x1c': ASCII/Unicode U+001C (category Cc: Other, control)
 '\x1d': ASCII/Unicode U+001D (category Cc: Other, control)
 '\x1e': ASCII/Unicode U+001E (category Cc: Other, control)
 '\x1f': ASCII/Unicode U+001F (category Cc: Other, control)
 '\x7f': ASCII/Unicode U+007F (category Cc: Other, control)

挑战 filter(iscntrl, chars_range) 筛选创建的范围,并仅返回那些作为控制字符的字符。 功能 iscntrl 申报表 true 如果该字符属于Unicode分类中的"Cc:其他,控制"类别。 结果写入变量 control_chars,其中将包含33个元素的向量-所有控制ASCII字符。

结果分析

代码执行结果:
-获得33个元素的向量
-所有元素都是ASCII控制字符
-结果中包含代码为0-31和127的字符
-某些符号由特殊符号表示(例如, \n, \t, \r),和其他十六进制代码(\x01, \x1f)

结论

在这个例子中,我们研究了如何使用内置的Julia语言函数来过滤控制ASCII字符。 我们创建了一个所有ASCII字符的范围,然后应用了函数 filter 用谓词 iscntrl 以仅突出显示控制字符。 当需要识别或删除可能影响程序格式或正确操作的不可见控制字符时,此技术在文本处理中很有用。 理解这些符号对于使用文本数据、解析器、终端I/O或系统编程的开发人员非常重要。

该示例是使用[罗塞塔代码]的材料开发的(https://rosettacode.org/wiki/ASCII_control_characters