我會創建關鍵字列表,然後通過查找這些關鍵字的索引內數據開始,如果存在。 (我重新排列了關鍵字出現在數據的順序來演示稍後的一點)。
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中的數據'}
OP詢問如何解析他的字符串。它存儲在MongoDB中的事實是切合實際的。 –
感謝您的建議!我同意我可能需要做多次傳球。我並不擔心數據庫部分,因爲這與我對如何實際分析這些數據的問題沒有那麼相關。我覺得我可以用非常愚蠢的方式做到這一點(可能效率低下,不能處理所有數據),但是我想知道是否有更好的方法來做到這一點。 – Jason
編輯答案包括鏈接到're.findAll' – user2926055