我有一个包含字符串的元组列表。我想根据特定的分隔符将字符串拆分成更小的字符串并删除某些字符。
item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..]
# this is how each of the strings inside the tuples look like
str1 = 'apple OR orange AND NOT pineapple'
str2 = '(sugar and salt) or (pepper and vinegar)'
期望的结果:
cleaned_list = [['apple', 'orange', 'pineapple'], ['sugar', 'salt', 'pepper', 'vinegar',..]
# This is how each of the list should look like after splitting
list1 = ['apple', 'orange', 'pineapple']
list2 = ['sugar', 'salt', 'pepper', 'vinegar']
这是我试过的
# Delimiter: 'AND', 'and', 'OR', 'or', 'NOT', 'not'
# Characters to remove: '[', ']', '(', ')'
test = item_list.replace('(', '').replace(')', '')).split(' AND ')
当我想在字符串中拆分多个分隔符时,它会变得有点棘手。有更简单的方法吗?
请您参考如下方法:
Python 代码
您可以将 re.split 与 strip 一起使用(假设单词中间可以有空格)
>>> item_list = [('apple OR ora nge AND NOT pineapple'), ('(sugar and salt) or (pepper and vinegar)')]
>>> [[x.strip() for x in re.split(r'(?i)(?:\b(?:AND|OR|NOT)\b|[]\[()])', x) if x.strip()] for x in item_list]
[['apple', 'ora nge', 'pineapple'], ['sugar', 'salt', 'pepper', 'vinegar']]
