加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi:像Python一样编码字符串

发布时间:2020-12-15 09:30:58 所属栏目:大数据 来源:网络整理
导读:我想像 Python那样对字符串进行编码. Python代码是这样的: def EncodeToUTF(inputstr): uns = inputstr.decode('iso-8859-2') utfs = uns.encode('utf-8') return utfs 这很简单. 但是在Delphi中,我不明白,如何编码,先强制好字符集(无论我们拥有哪台计算机)
我想像 Python那样对字符串进行编码.

Python代码是这样的:

def EncodeToUTF(inputstr):
  uns = inputstr.decode('iso-8859-2')
  utfs = uns.encode('utf-8')
  return utfs

这很简单.

但是在Delphi中,我不明白,如何编码,先强制好字符集(无论我们拥有哪台计算机).

我试过这个测试代码来看转换:

procedure TForm1.Button1Click(Sender: TObject);
var
    w : WideString;
    buf : array[0..2048] of WideChar;
    i : integer;
    lc : Cardinal;
begin
    lc := GetThreadLocale;
    Caption := IntToStr(lc);
    StringToWideChar(Edit1.Text,buf,SizeOF(buf));
    w := buf;
    lc := MakeLCID(
        MakeLangID( LANG_ENGLISH,SUBLANG_ENGLISH_US),0);
    Win32Check(SetThreadLocale(lc));
    Edit2.Text := WideCharToString(PWideChar(w));
    Caption := IntToStr(AnsiCompareText(Edit1.Text,Edit2.Text));
end;

输入是:“árvízt?r?tük?rfúrógép”,匈牙利口音测试词组.
当地的lc是1038(hun),新的lc是1033.

但这次每次都会得到0个结果(相同的字符串),并且重音是相同的,我不会丢失??这不是英语朗.

我做错了什么?我如何做与Python相同的事情?

感谢您的帮助,链接等:
???DD

解决方法

Windows对ISO-8859-2使用代码页28592.如果您有一个包含ISO-8859-2编码字节的缓冲区,则必须先将字节解码为UTF-16,然后将结果编码为UTF-8.根据您使用的Delphi版本,您可以:

1)在D2009之前,使用MultiByteToWideChar()和WideCharToMultiByte():

function EncodeToUTF(const inputstr: AnsiString): UTF8String;
var
  ret: Integer;
  uns: WideString;
begin
  Result := '';
  if inputstr = '' then Exit;
  ret := MultiByteToWideChar(28592,PAnsiChar(inputstr),Length(inputstr),nil,0);
  if ret < 1 then Exit;
  SetLength(uns,ret);
  MultiByteToWideChar(28592,PWideChar(uns),Length(uns));
  ret := WideCharToMultiByte(65001,Length(uns),nil);
  if ret < 1 then Exit;
  SetLength(Result,ret);
  WideCharToMultiByte(65001,PAnsiChar(Result),Length(Result),nil);
end;

2a)在D2009上,使用SysUtils.TEncoding.Convert():

function EncodeToUTF(const inputstr: RawByteString): UTF8String;
var
  enc: TEncoding;
  buf: TBytes;
begin
  Result := '';
  if inputstr = '' then Exit;
  enc := TEncoding.GetEncoding(28592);
  try
    buf := TEncoding.Convert(enc,TEncoding.UTF8,BytesOf(inputstr));
    if Length(buf) > 0 then
      SetString(Result,PAnsiChar(@buf[0]),Length(buf));
  finally
    enc.Free;
  end;
end;

2b)在D2009上,或者定义一个新的字符串typedef,将数据放入其中,并将其分配给UTF8String变量.无需手动编码/解码,RTL将为您处理所有事情:

type
  Latin2String = type AnsiString(28592);

var
  inputstr: Latin2String;
  outputstr: UTF8String;
begin
  // put the ISO-8859-2 encoded bytes into inputstr,then...
  outputstr := inputstr;
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读