我需要从客户视图列表创建一个字典



我有一个字符串如下

[t] color[+1]##这只手表的颜色很漂亮。颜色是红色的,非常明亮。##上一款的颜色是有限的,但这一款的颜色种类更多。尺寸[-1]##尺寸限于中号和大号。##手表尺寸可通过表带调节

我需要按如下方式创建一个字典:

watch = {color[+1]:['这只手表的颜色很漂亮。’、‘颜色是红色的,很鲜艳。上一款的颜色有限,但这一款的颜色种类更多,尺寸:[-1]尺寸仅限于中号和大号。', '手表大小可通过表带调节。']}

我能够通过'##'进行分割,并且我能够使用使用'w*[[+|-]{1}d]'的正则表达式匹配模式(颜色[+1}),但是提取两个字符串以创建字典是我与

斗争的地方

这段代码将完成任务。

str = "[t] color[+1]##The colors of the watch is very beautiful.##The color is red and very bright.##The color of the previous model, was limited but with this edition it comes with a larger variety of colors. size[-1]##size is limited to medium and large. ##The watch size can be adjusted through the band."
strlist=  str.replace("[t]","").replace(". ","##").split("##")
dictionary = {}
count  = -1
new_key = ""
for i in strlist:
if not i.strip():
continue
if "[" in i and "]" in i:
count = count + 1
new_key = i.strip()
dictionary[new_key] = []
else:
dictionary.get(new_key).append(i)
print(dictionary)

结果如下。

{'color[+1]': ['The colors of the watch is very beautiful.', 'The color is red and very bright.', 'The color of the previous model, was limited but with this edition it comes with a larger variety of colors'], 'size[-1]': ['size is limited to medium and large', 'The watch size can be adjusted through the band.']}

最新更新