給定一個停用詞串列和一個字串:
list_stop_words = ['for', 'the', 'with']
mystring = 'this is the car for the girl with the long nice red hair'
我想讓文本從結尾開始到串列的第一個停止詞。
預期結果“長長的漂亮的紅頭發”
我嘗試了幾個 for 回圈,但它非常麻煩,應該有一個直接的方法,甚至可能是一個單行。
我超級冗長的解決方案:
list_stop_words = ['for', 'the', 'with']
mystring = 'this is the car for the girl with the long nice red hair'
reversed_sentence =mystring.split()[::-1]
for i,word in enumerate(reversed_sentence):
if word in list_stop_words:
position = i
words = reversed_sentence[0:i 1]
print(' '.join(words[::-1]))
break
for word in mastering[::-1]:
對更好的方法有什么建議嗎?
回答后編輯(見下文)

uj5u.com熱心網友回復:
你可以試試這樣的
mystring[max([mystring.rfind(stop_word) for stop_word in list_stop_words]):]
基本上你找到每個單詞的最后一次出現rfind然后你從所有單詞中找到最后一個 max 然后你把它切掉
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336729.html
