计算 swift 中 url 的字数

Calculating word count from a url in swift

我正在创建一个阅读列表应用程序,我想将添加 link 的用户的阅读时间传递到他们阅读列表中的 table 单元格 - 这是唯一的方法从该页面的字数中获取该数字。我找到了一些解决方案,即 Parsehub,Parse and Mercury,但它们似乎更适合需要从 url 中抓取更高级内容的用例。 Swift 中是否有更简单的方法来计算 url 的字数?

首先,你需要解析HTML。 HTML 只能使用专用的 HTML 解析器进行可靠解析。请不要使用正则表达式或任何其他搜索方法来解析 HTML。你可以从这个 link. If you are using swift, you may try Fuzi or Kanna 中读到原因。在使用任何一个库获得正文后,您必须删除多余的空格并计算单词数。我已经用 Fuzi 库编写了一些基本代码供您入门。

import Fuzi

// Trim
func trim(src:String) -> String {
    return src.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}

// Remove Extra double spaces and new lines
func clean(src:String) ->String {
    return src.replacingOccurrences(
        of: "\s+",
        with: " ",
        options: .regularExpression)
}


let htmlUrl = URL(fileURLWithPath: ((#file as NSString).deletingLastPathComponent as NSString).appendingPathComponent("test.html"))
do {
    let data = try Data(contentsOf: htmlUrl)
    let document = try HTMLDocument(data: data)
    // get body of text
    if let body = document.xpath("//body").first?.stringValue {
        let cleanBody = clean(src: body)
        let trimmedBody = trim(src:cleanBody)
        print(trimmedBody.components(separatedBy: " ").count)
    }
} catch {
    print(error)
}

如果您喜欢,可以将我的全局函数更改为 String 扩展名,或者您可以将它们组合成一个函数。为了清楚起见,我写了它。