【问题标题】:Calculating word count from a url in swift快速计算来自 url 的字数
【发布时间】:2017-08-18 20:58:03
【问题描述】:

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

【问题讨论】:

    标签: ios swift parsing html-parsing


    【解决方案1】:

    首先,您需要解析 HTML。只有使用专用的 HTML 解析器才能可靠地解析 HTML。请不要使用正则表达式或任何其他搜索方法来解析 HTML。您可以从link 中了解原因。如果你使用 swift,你可以试试FuziKanna。使用任何一个库获得正文后,您必须删除多余的空格并计算单词。我已经用 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 扩展名,或者您可以将它们组合成一个函数。为了清楚起见,我写了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2016-02-21
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 2010-12-23
      相关资源
      最近更新 更多