1 回答
TA贡献1817条经验 获得超6个赞
总有蛮力方法可以解决这个问题。我正在寻找一些聪明的东西。
def expand_by_conjuction(item):
def get_slash_index(item):
for num , ele in enumerate(item):
if "/" in ele:
return num
items = [item]
while any([True for item in items for ele in item if "/" in ele]):
for item in items:
item_org = item
item = item.split()
if any([ True for ele in item if "/" in ele]):
sls_index = get_slash_index(item)
split_conjucted = item[sls_index].split("/")
for idx, part in enumerate(split_conjucted):
n_item = []
n_item += item[:sls_index]
n_item.append(part)
sls_p1 = sls_index +1
if not sls_p1 > len(item):
n_item += item[sls_p1:]
n_item = " ".join(n_item)
#print(n_item)
items.append(n_item)
if item_org in items:
items.remove(item_org)
return items
def slashize_conjuctions(item):
slashize = [' or ', ' and ', ' and/or ', ' or/and ', ' & ']
for conj in slashize:
if conj in item:
item = item.replace(conj,"/")
return item
items = ['bag of apples/oranges', 'case of citrus (lemon or limes)',
'chocolates/candy box' , 'bag of shoes & socks',
'pear red/brown/green', 'match box and/or lighter',
'milkshake (soy and almond) added ']
new_items = []
for string in items:
item = slashize_conjuctions(string)
lst = expand_by_conjuction(item)
lst = [ele.replace("(","").replace(")","") for ele in lst]
[new_items.append(ele) for ele in lst]
#print(f'String:{string} ITEM:{item} --> list{lst}')
print(new_items)
添加回答
举报