2017-02-12 70 views
1

我有一个字符串,我想将其拆分成某些类型的列表。例如,我想分割Starter Main Course Dessert[Starter, Main Course, Dessert]在Python中分割字符串,但在子字符串中使用空格

我不能使用split(),因为它会分割Main Course类型。我怎么做分裂?是否需要正则表达式?

+0

你将不得不为了做到这一点要知道无论是词或部分词,或布局.. – TheLazyScripter

+0

匹配什么'主要Course'但不是'初学者Main'或'场Dessert'(从'初学者主菜甜点')?这是不可能的,AFAIK。 – Dev

+0

是的,我知道我想分裂成的词,但我不知道如何从原始字符串中做到这一点 –

回答

3

如果你有可以接受的单词的列表,你可以使用正则表达式工会:

import re 

acceptable_words = ['Starter', 'Main Course', 'Dessert', 'Coffee', 'Aperitif'] 
pattern = re.compile("("+"|".join(acceptable_words)+")", re.IGNORECASE) 
# "(Starter|Main Course|Dessert|Coffee|Aperitif)" 

menu = "Starter Main Course NotInTheList dessert" 
print pattern.findall(menu) 
# ['Starter', 'Main Course', 'dessert'] 

如果你只是想指定特殊子应该匹配,你可以使用:

acceptable_words = ['Main Course', '\w+'] 
0

我认为只指定'特殊'两个单词标记更实用。

special_words = ['Main Course', 'Something Special'] 
sentence = 'Starter Main Course Dessert Something Special Date' 

words = sentence.split(' ') 
for i in range(len(words) - 1): 
    try: 
     idx = special_words.index(str(words[i]) + ' ' + words[i+1]) 
     words[i] = special_words[idx] 
     words[i+1] = None 
    except ValueError: 
     pass 

words = list(filter(lambda x: x is not None, words)) 
print(words)