【问题标题】:Unicode-aware strings(1) programUnicode 感知字符串(1) 程序
【发布时间】:2010-10-09 08:27:05
【问题描述】:

是否有人提供可识别 unicode 的字符串程序的代码示例?编程语言无关紧要。我想要的东西本质上与 unix 命令“字符串”做同样的事情,但它也适用于 unicode 文本(UTF-16 或 UTF-8),拉动英语字符和标点符号的运行。 (我只关心英文字符,不关心其他字母)。

谢谢!

【问题讨论】:

  • 仅适用于英文和 UTF-8,strings(1) 应该已经可以了。
  • 如果语言无关紧要,为什么不检查字符串实用程序本身的来源?

标签: string unicode


【解决方案1】:

我遇到了类似的问题并尝试了“strings -e ...”,但我刚刚找到了修复宽度字符编码的选项。 (UTF-8 编码是可变宽度的)。

请记住,ascii 之外的默认字符需要额外的strings 选项。这包括几乎所有非英语语言字符串。

尽管如此,“-e S”(单个 8 位字符)输出包括 UTF-8 字符。

我写了一个非常简单的 Perl 脚本,它应用了一个 "strings -e S ... | iconv ..." 到输入文件。

我相信针对特定限制进行调整很容易。 用法:utf8strings [options] file*

#!/usr/bin/perl -s

our ($all,$windows,$enc);   ## use -all ignore the "3 letters word" restriction
use strict;
use utf8::all;

$enc = "ms-ansi" if     $windows;  ##
$enc = "utf8"    unless $enc    ;  ## defaul encoding=utf8
my $iconv = "iconv -c -f $enc -t utf8 |";

for (@ARGV){ s/(.*)/strings -e S '$1'| $iconv/;}

my $word=qr/[a-zçáéíóúâêôàèìòùüãõ]{3}/i;   # adapt this to your case

while(<>){
   # next if /regular expressions for common garbage/; 
   print    if ($all or /$word/);
}

在某些情况下,这种方法会产生一些额外的垃圾。

【讨论】:

    【解决方案2】:

    您只是想使用它,还是出于某种原因坚持代码?

    在我的 Debian 系统上,strings 命令似乎可以立即执行此操作。请参阅手册页中的摘录:

      --encoding=encoding
           Select the character encoding of the strings that are to be found.  Possible values for encoding are: s = single-7-bit-byte characters (ASCII, ISO  8859,
           etc.,  default),  S  = single-8-bit-byte characters, b = 16-bit bigendian, l = 16-bit littleendian, B = 32-bit bigendian, L = 32-bit littleendian. Useful
           for finding wide character strings.
    

    编辑:好的。我不懂 C#,所以这可能有点麻烦,但基本上,您需要搜索交替的零和英文字符的序列。

    byte b;
    int i=0;
    while(!endOfInput()) {
      b=getNextByte();
    LoopBegin:
      if(!isEnglish(b)) {
        if(i>0) // report successful match of length i
        i=0;
        continue;
      }
      if(endOfInput()) break;
      if((b=getNextByte())!=0)
        goto LoopBegin;
      i++; // found another character
    }
    

    这应该适用于小端。

    【讨论】:

    • 我需要代码...我需要将它合并到我正在编写的系统中(如果重要的话,在 c# 中)。
    • 谢谢,正是我需要的。很明显,现在我想起来了;跳过空字节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2023-01-10
    • 2023-03-07
    相关资源
    最近更新 更多