如果一个句子包含来自a的两个以上元素,并且用逗号分隔,我想将逗号分开。
a = ['benz','bmw','apple','salmon']
sen = "I like benz, but I like bmw more"
代码:
i=0
for car in a:
if car in sen and "," in sen:
i+=1
if i>1:
print(sen.split(","))
结果:
['I like benz', ' but I like bmw more']
但是如果我的句子看起来像这样:
sen="I like benz but I like bmw more, what about you?"
然后,我不想拆分句子,因为benz和bmw没有用逗号分隔。有什么方法可以区分句子是否由“ .... [word]” .... +“,” + ....“ [word] ......”构成?
答案 0 :(得分:2)
def split_sentence(sen):
words = ['benz','bmw','apple','salmon']
split = sen.split(",") #split the string and check if words exists in both sentence
flag = 0
for s in split:
for w in words:
if w in s:
flag+=1
break
if flag == len(split):
return split
return sen
sen="I like benz but I like bmw more, what about you?"
# sen = "I like benz, but I like bmw more"
print(split_sentence(sen))
应该返回
情况1:
I like benz but I like bmw more, what about you?
案例II:
['I like benz', ' but I like bmw more']
答案 1 :(得分:0)
也许更简单的方法就足够了吗?
dictionary = ['benz','bmw','apple','salmon']
sentence = "I like benz, but I like bmw more"
if __name__ == '__main__':
included_words = [word for word in dictionary if word in sentence]
if len(included_words) == 2:
print(sentence, included_words)
输出:
I like benz, but I like bmw more ['benz', 'bmw']