【问题标题】:How to detect emoji as unicode in Perl?如何在 Perl 中将表情符号检测为 unicode?
【发布时间】:2018-06-04 03:10:31
【问题描述】:

我有包含 emoji unicode 字符的文本文件,例如 ????、☹️、????、????、????、????、????、???? .

例如代码 \N{1F60D} 对应于 ???? 我使用 https://perldoc.perl.org/perluniintro.html 创建 Unicode 部分中的推荐。 我的程序必须检测到它们并进行一些处理,但如果我使用

open(FIC1, ">$fic");

while (<FIC>) {
my $ligne=$_;

if( $ligne=~/\N{1F60D}/  )
{print "heart ";
    }
}

现在我这样做了,它工作了

open(FIC1, ">$fic");

while (<FIC>) {
my $ligne=$_;

if( $ligne=~/????/  )
{print "Heart ";
    }
}

第一个代码有什么问题 问候

【问题讨论】:

  • 您使用的是哪个版本的 perl? perl -v 和哪个平台?
  • @Flying_whale:我按照你的建议做了一切,但没有任何改变。
  • @Nahuel Fouilleul : 这是为 MSWin32-x64-multi-thread 构建的 perl 5,版本 22,subversion 1 (v5.22.1)
  • 看我的回答添加-C选项
  • 请注意 U+\N{ .. } 之间缺失

标签: perl unicode emoji


【解决方案1】:

为了检测表情符号,我会在正则表达式中使用 unicode 属性,例如:

  • \p{Emoticons}
  • \p{Block: Emoticons}

例如,只打印出表情符号

perl -CSDA -nlE 'say for( /(\p{Emoticons})/g )' <<< 'abc???αβγ'

将打印

?
?
?

欲了解更多信息,请参阅perluniprops

【讨论】:

    【解决方案2】:

    如果您查看 perldoc perlre 中的 \N,您会发现它的意思是“命名的 Unicode 字符或字符序列”。

    你可以改用这个:

    if ($ligne =~ m/\N{U+1F60D}/)
    # or
    if ($ligne =~ m/\x{1F60D}/)
    

    编辑:您发布的链接中也有描述, https://perldoc.perl.org/perluniintro.html

    编辑: 您阅读的内容可能未解码。你想要:

    use Encode;
    ...
    my $ligne = decode_utf8 $_;
    

    或者直接以utf8模式直接打开文件:

    open my $fh, "<:encoding(UTF-8)", $filename or die "Could not open $filename: $!";
    while (my $ligne = <$fh>) {
        if ($ligne =~ m/\N{U+1F60D}/) { ... }
    }
    

    您从未展示过如何打开名为 FIC 的文件句柄,所以我认为它是 utf8 解码的。 这是另一个关于 perl 中 unicode 的好教程:https://perlgeek.de/en/article/encodings-and-unicode

    【讨论】:

    • 对不起,这也行不通,是一样的,你只是加了m。我也用 \x 测试过,但不工作。
    • 我不仅加了m。请仔细看看。我加了U+
    • 非常感谢,问题是文件的打开方式,所以解决了我的问题是命令 my $ligne = decode_utf8 $_; ,谢谢
    【解决方案3】:

    使用perl -C可用于启用unicode功能

    perl -C -E 'say "\N{U+263a}"'|perl -C -ne 'print if /\N{U+263a}/'
    

    from perl run

    -C [编号/列表]

    -C 标志控制一些 Perl Unicode 功能。 ...

    第二个代码起作用的原因是perl匹配UTF-8二进制序列:如perl -ne 'print if /\xf0\x9f\x98\x8d/'

    以下应该可以工作

    #!/usr/bin/perl -C
    open(FIC1, ">$fic");
    
    while (<FIC>) {
        my $ligne=$_;
    
        if( $ligne=~/\N{U+1F60D}/  ) {
            print "heart ";
        }
    }
    

    【讨论】:

    • 我尝试 perl -C,但什么也没发生,需要很长时间,我认为这阻塞了终端,如果我在我的程序中添加 #!/usr/bin/perl -C,但我有同样的结果,第二个命令我不明白怎么用
    • 给出的例子是从命令行测试,没有 -e 或 -E + 命令 perl 程序正在等待输入以读取命令,如果它不起作用可能是因为 @987654326 @失踪
    猜你喜欢
    • 2015-10-18
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2012-01-27
    • 2019-12-25
    • 1970-01-01
    相关资源
    最近更新 更多