2017-03-26 31 views
0

我正在創建一個閱讀列表應用程序,並且我想將用戶添加鏈接的閱讀時間傳遞給閱讀列表中的表格單元格,該數字來自該頁面的字數。我發現了幾個解決方案,分別是Parsehub,ParseMercury,但它們似乎更適合需要更高級的東西從url中獲取的用例。在Swift中有更簡單的方法來計算url的字數嗎?從swift中計算字詞計數

回答

0

首先,您需要解析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延伸,也可以在一個單一的功能,將它們結合起來。爲了清楚起見,我寫了它。

+0

謝謝助手!真的很有幫助 – Dominic