2016-03-09 58 views
0

我設法通過scrapy抓取大量數據,並且所有數據當前都以JSON對象的形式存儲在MongoDB中。我主要想知道如何有效地解析和理解數據。我想將數據提取到小節中。例如,假裝我有作爲數據存儲:通過抓取數據解析的最佳方法

{ 
    "data": "category 1: test test \n category2: test test \n test test \n category 3: test test test \n category 4: this is data in category 4 " 
} 

基本上我想通過關鍵字去提取關鍵字,直到下一個關鍵詞之後到來的一切。所有類別1後的信息(「測試測試」)應存儲在「類別1」下。對於類別順序沒有真正的押韻或節奏,也沒有每個類別之後的文本數量,但所有類別都在那裏。

我想知道是否有任何庫可以用來編寫腳本來執行此操作或任何可以自動爲我執行此操作的工具。要麼是一個資源指針,我可以學習如何做這樣的事情。

回答

-2

這聽起來像一個足夠特定的任務,你可能需要做另一個數據處理。 pymongo是我的首選庫,用於與python中的Mongo數據庫中的數據進行交互(並且是mongodb本身推薦的)。

爲了解析字符串中去,讀了正則表達式,特別是.findall方法:

>>> import re 
>>> data_string = "category 1: test test \n category2: test test \n test test \n category 3: test test test \n category 4: this is data in category 4 " 
>>> m = re.findall(r'(category\s*\d+): (.*)', data_string) 
>>> m 
[('category 1', 'test test '), ('category2', 'test test '), ('category 3', 'test test test '), ('category 4', 'this is data in category 4 ')] 
+0

OP詢問如何解析他的字符串。它存儲在MongoDB中的事實是切合實際的。 –

+0

感謝您的建議!我同意我可能需要做多次傳球。我並不擔心數據庫部分,因爲這與我對如何實際分析這些數據的問題沒有那麼相關。我覺得我可以用非常愚蠢的方式做到這一點(可能效率低下,不能處理所有數據),但是我想知道是否有更好的方法來做到這一點。 – Jason

+0

編輯答案包括鏈接到're.findAll' – user2926055

0

我會創建關鍵字列表,然後通過查找這些關鍵字的索引內數據開始,如果存在。 (我重新排列了關鍵字出現在數據的順序來演示稍後的一點)。

d = {"data": "category 1: test test \n category 3: test test test \n category2: test test \n test test \n category 4: this is data in category 4 " } 
keywords = ['category 1', 'category2', 'category 3', 'category 4'] 
kw_indices = [-1]*len(keywords) 
data = d['data'] 

for i in range(len(keywords)): 
    kw = keywords[i] 
    if kw in data: 
     kw_indices[i] = data.index(kw) 

kw_indices_sorted = sorted(kw_indices) 

數據找到的每個關鍵字的開始位置由它的值在kw_indices給出,其中-1表示該關鍵字不是在數據找到。

要了解每個關鍵字的結束索引,我們發現從下一個起始索引kw_indices_sorted列表,然後找出哪些關鍵字有開始索引,那麼獲得下一屆的起始索引值。

data_by_category = {} 
for j in range(len(keywords)): 
    kw = keywords[j] 

    if kw_indices[j] > -1: 
     # The keyword was found in the data and we know where in the string it starts 
     kw_start = kw_indices[j] 
     sorted_index = kw_indices_sorted.index(kw_start) 
     if sorted_index < len(kw_indices_sorted) - 1: 
      # This index is not the last/largest value in the list of sorted indices 
      # so there will be a next value. 
      next_kw_start = kw_indices[kw_indices.index(kw_indices_sorted[sorted_index + 1])] 
      kw_data = data[kw_start:next_kw_start] 
     else: 
      kw_data = data[kw_start:] 

     # If you don't want the keyword included in the result you can strip it out here 
     kw_data = kw_data.replace(kw + ':', '') 
     data_by_category[kw] = kw_data 
    else: 
     # The keyword was not found in the data, enter an empty value for it or handle this 
     # however else you want. 
     data_by_category[kw] = '' 

print(data_by_category) 

{ '類別1': '測試測試\ n', '類別2': '測試測試\ n個測試測試\ n', '類別3': '測試測試測試\ n',「類4':'這是類別4中的數據'}

相關問題