gpt4 book ai didi

html - 使用 Objective-C 将 HTML 文本转换为纯文本

转载 作者:IT王子 更新时间:2023-10-29 07:54:58 25 4
gpt4 key购买 nike

我有一个很大的 NSString,里面有 HTML 文本。此字符串的长度超过 3.500.000 个字符。我如何将此 HTML 文本转换为 NSString,其中包含纯文本。我正在使用 scanner ,但它工作得太慢了。有什么想法吗?

最佳答案

这取决于您的目标 iOS 版本。自 iOS7 以来,有一个内置方法不仅可以去除 HTML 标签,还可以将格式设置为字符串:

Xcode 9/ swift 4

if let htmlStringData = htmlString.data(using: .utf8), let attributedString = try? NSAttributedString(data: htmlStringData, options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil) {
print(attributedString)
}

您甚至可以像这样创建一个扩展:

extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = self.data(using: .utf8) else {
return nil
}

do {
return try NSAttributedString(data: data, options: [.documentType : NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("Cannot convert html string to attributed string: \(error)")
return nil
}
}
}

请注意,此示例代码使用 UTF8 编码。您甚至可以创建一个函数而不是计算属性,并将编码添加为参数。

swift 3

let attributedString = try NSAttributedString(data: htmlString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)

objective-C

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];

如果您只需要删除 < 之间的所有内容和 > (肮脏的方式!!!),如果字符串中有这些字符,这可能会有问题,请使用:

- (NSString *)stringByStrippingHTML {
NSRange r;
NSString *s = [[self copy] autorelease];
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}

关于html - 使用 Objective-C 将 HTML 文本转换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19226634/

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