我有一个文本框,将只填充表情符号。没有任何类型的空格或字符。我需要拆分这些表情符号来识别它们。这就是我尝试过的:
function emoji_to_unicode(){
foreach ($emoji in $textbox.Text) {
$unicode = [System.Text.Encoding]::Unicode.GetBytes($emoji)
Write-Host $unicode
}
}
循环不是一个一个地打印字节,而是只运行一次,打印所有表情符号的代码。好像所有的表情符号都是一个项目。我用6个表情符号进行测试,而不是得到这个:
61 216 7 222
61 216 67 222
61 216 10 222
61 216 28 222
61 216 86 220
60 216 174 223
我明白了:
61 216 7 222 216 67 222 61 216 10 222 61 28 222 216 86 220 60 216 174 223
我遗漏了什么?
发布于 2020-06-15 15:41:09
字符串只是一个元素。您希望将其更改为字符数组。
foreach ($i in 'hithere') { $i }
hithere
foreach ($i in [char[]]'hithere') { $i }
h
i
t
h
e
r
e
嗯,这不太好。这些代码点非常高,U+1F600 (32位)等等。
foreach ($i in [char[]]'') { $i }
� # 16 bit surrogate pairs?
�
�
�
�
�
�
�
�
�
�
�
�
�
好吧,把每一双都加起来。下面是另一种使用https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates (或只使用ConvertToUTF32($emoji,0) )的方法。
$emojis = ''
for ($i = 0; $i -lt $emojis.length; $i += 2) {
[System.Char]::IsHighSurrogate($emojis[$i])
0x10000 + ($emojis[$i] - 0xD800) * 0x400 + $emojis[$i+1] - 0xDC00 | % tostring x
# [system.char]::ConvertToUtf32($emojis,$i) | % tostring x # or
$emojis[$i] + $emojis[$i+1]
}
True
1f600
True
1f601
True
1f602
True
1f603
True
1f604
True
1f605
True
1f606
注意,Unicode.GetBytes()方法调用中的unicode引用了utf16le编码。
中国作品。
[char[]]'嗨,您好'
嗨
,
您
好
这里使用的是utf32编码。所有字符都有4个字节长。将每4个字节转换成一个int32,并将它们打印为十六进制。
$emoji = ''
$utf32 = [System.Text.Encoding]::utf32.GetBytes($emoji)
for($i = 0; $i -lt $utf32.count; $i += 4) {
$int32 = [bitconverter]::ToInt32($utf32[$i..($i+3)],0)
$int32 | % tostring x
}
1f600
1f601
1f602
1f603
1f604
1f605
1f606
或者从int32转到字符串。简单地将int32转换为[char]
不起作用(必须添加char的对)。脚本引用:https://www.powershellgallery.com/packages/Emojis/0.1/Content/Emojis.psm1
for ($i = 0x1f600; $i -le 0x1f606; $i++ ) { [System.Char]::ConvertFromUtf32($i) }
另见How to encode 32-bit Unicode characters in a PowerShell string literal?
编辑:
Powershell 7有一个很好的枚举数()方法:
$emojis = ''
$emojis.enumeraterunes() | % value | % tostring x
1f600
1f601
1f602
1f603
1f604
1f605
1f606
https://stackoverflow.com/questions/62391665
复制相似问题