我会创建关键字列表,然后通过查找这些关键字的索引内数据开始,如果存在。 (我重新排列了关键字出现在数据的顺序来演示稍后的一点)。
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