gpt4 book ai didi

swift euc-kr 韩语编码不起作用。但可以在 python 中使用

转载 作者:行者123 更新时间:2023-11-30 12:48:51 25 4
gpt4 key购买 nike

我正在编写一些代码来解析使用 euc-kr 韩语编码器编码的服务器中的韩语文本。

当我在 Python 中进行相同的编码时,它会按预期工作。但是当我按照以下方式执行时,编码不起作用。结果是不可读的。

在Python中:

string = u'안녕하세요.'.encode('eucKR') 

在 swift :

let encoding:UInt =  CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(
CFStringEncodings.EUC_KR.rawValue))

let encodedData = "안녕하세요.".data(using: String.Encoding(rawValue: encoding))!

这两种编码有什么区别?

以下是 python 和 swift 的完整源代码。我仍然停留在编码部分。问题是否与 alamofire post 请求有关?

Python:

import requests
from pattern import web

string = u'저는 내일 바빠서 학교에 못갑니다.'.encode('eucKR')
r = requests.post("http://nlp.korea.ac.kr/~demo/dglee/komatag.php", data={'formradio1': '', 'formradio2': 'ems', 'textarea': string})
dom = web.Element(r.text)
main = dom('tr')
for item in main:
result = web.plaintext(item.source)
a = result.encode('ISO-8859-1')
t=a.decode('eucKR')
print(t)

swift :

    override func viewDidLoad() {

let string: NSString = NSString(string: "안녕하세요")
let encodedEucKr = stringToEuckrString(stringValue: string as String)
print(encodedEucKr)

Alamofire.request("http://nlp.korea.ac.kr/~demo/dglee/komatag.php", method: .post, parameters: ["formradio1":"", "formradio2":"ems", "textarea": encodedEucKr], headers: nil).responseString { response in

switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break

case .failure(_):
print(response.result.error)
break

}
}

}


func stringToEuckrString(stringValue: String) -> String {

let encoding:UInt = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(
CFStringEncodings.EUC_KR.rawValue))

let encodedData = stringValue.data(using: String.Encoding(rawValue: encoding))!

let attributedString = try? NSAttributedString(data: encodedData, options:[:], documentAttributes: nil)

if let _ = attributedString {
return attributedString!.string
} else {
return ""
}
}

最佳答案

这并不容易,有两个原因......

  1. 在现代网络技术和标准中,发送 EUC-KR 格式的表单数据不被认为是符合标准的。

  2. 从您的服务器发送的响应有点损坏,因为 Swift 无法将结果解码为有效的 EUC-KR 文本。

    (这似乎是您的服务器端代码的错误。)

无论如何,当您需要向 EUC-KR 中的服务器发送基于 Web 表单的请求时:

  • 从原始字节序列创建 EUC-KR 字节序列
  • 百分号转义它。您可能需要自己完成
  • 将整个请求放入 HTTP 请求正文
  • 添加正确的 MIME 类型 header

一些细节取决于服务器。我从来没有使用过Alamofire,所以我不知道Alamofire是否支持这样的东西。

这里我向您展示一个使用普通 URLSession 的示例:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
sendRequest(string: "안녕하세요")
}

func sendRequest(string: String) {
let rawEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.EUC_KR.rawValue))
let encoding = String.Encoding(rawValue: rawEncoding)

let url = URL(string: "http://nlp.korea.ac.kr/~demo/dglee/komatag.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
//Create an EUC-KR byte sequece
let eucKRStringData = string.data(using: encoding) ?? Data()
//Percent-escape, you need to do it by yourself
//(Though, most servers accept non-escaped binary data with its own rules...)
let eucKRStringPercentEscaped = eucKRStringData.map {byte->String in
if byte >= UInt8(ascii: "A") && byte <= UInt8(ascii: "Z")
|| byte >= UInt8(ascii: "a") && byte <= UInt8(ascii: "z")
|| byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9")
|| byte == UInt8(ascii: "_") || byte == UInt8(ascii: ".") || byte == UInt8(ascii: "-")
{
return String(Character(UnicodeScalar(UInt32(byte))!))
} else if byte == UInt8(ascii: " ") {
return "+"
} else {
return String(format: "%%%02X", byte)
}
}.joined()
//In application/x-www-form-urlencoded format, you send data in a URL-query like format.
let paramString = "formradio1=&formradio2=ems&textarea=\(eucKRStringPercentEscaped)"
//As all non-ASCII characters are percent-escaped, .isoLatin1 works well here.
let bodyData = paramString.data(using: .isoLatin1)!
//Form data needs to be sent as a body of HTTP protocol.
request.httpBody = bodyData
//MIME type for usual form data is "application/x-www-form-urlencoded".
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//URLRequest is ready and you can start dataTask here.
let task = URLSession.shared.dataTask(with: request) {data, response, error in
if let error = error {
print("Error:", error)
}
if let response = response {
print("Response:", response)
}
//The response may not be valid EUC-KR; you need to decode it while accepting invalid bytes.
if let data = data {
var result = ""
var i = 0
while i < data.count{
let ch = data[i]
if ch < 0x80 {
result += String(Character(UnicodeScalar(UInt32(ch))!))
} else if
i + 2 <= data.count,
let ch2 = String(data: data.subdata(in: i..<i+2), encoding: encoding)
{
result += ch2
i += 1
} else {
result += "?"
}
i += 1
}
print("Result:", result)
}
}
//Do not forget to resume the created task.
task.resume()
//And remember you should not do anything after you invoke an async task.
}

如果您的服务器端可以正确处理 UTF-8 请求和响应,上面的代码可能会简单得多。在 Web 服务中使用 EUC-KR 有点过时了。你最好尽快采用 UTF-8。

关于swift euc-kr 韩语编码不起作用。但可以在 python 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com