我是 python 的新手,正在嘗試解決這個問題。
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
output: I adding Guidebook
在這里我想將串列元素與字串進行匹配,并從字串中獲取下一個單詞來構造一個新單詞。
我試圖通過將單詞分成串列并檢查它們是否在串列中來做到這一點。但是'Plus'不會因為','而匹配,而且還有兩個'the'但我只需要在'the'之后得到最后一個詞
uj5u.com熱心網友回復:
一種方法是使用正則運算式string按單詞拆分(使用的模式是[\w] )。然后你可以建立一個詞對的字典,這樣你就可以查找第一個詞來檢索后面的詞。
import re
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
string_splits = re.findall(r'[\w] ',string)
pairs = {x:y for x,y in zip(map(lambda x: x.lower(), string_splits), string_splits[1:])}
print(' '.join(pairs.get(word.lower()) for word in words))
編輯以擴展字典的理解;
pairs = {}
for x,y in zip(map(lambda x: x.lower(), string_splits), string_splits[1:]):
pairs[x] = y
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535266.html
標籤:Python细绳
上一篇:StringBuilder的StringUtils?
下一篇:遍歷串列并將新行附加到資料框
