我有一組關鍵字:
keyword_list = ['word1', 'anotherWord', 'wordup', 'word to your papa']
我有一串文字:
string_of_text = 'So this is a string of text. I want to talk about anotherWord...and then I'm going to say something I've been meaning to say "wordup". But I also wanted to say the following: word to your papa. And lastly I wanted to talk about word1...'
我想回傳以下內容:
{'list_word': 'word1', 'string_of_text_after': '...'}, {'list_word': 'anotherWord', 'string_of_text_after': '...and then I'm going to say something I've been meaning to say "'}, {'list_word': 'wordup', 'string_of_text_after': '". But I also wanted to say the following: '}, {list_word: 'word to your papa', 'string_of_text_after':'. And lastly I wanted to talk about '}
正如您所看到的,它是一個帶有串列詞的字典串列,然后是串列詞項之后的文本,但只有在檢測到下一個串列詞之前,它才會停止。
在 python 中執行此操作的最有效方法是什么(python 3 或更高版本,如果不推薦使用的方法有任何問題,2 也可以)。
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
keyword_list = ['word1', 'anotherWord', 'wordup', 'word to your papa']
string_of_text = """So this is a string of text. I want to talk about anotherWord...\
and then I'm going to say something I've been meaning to say "wordup".\
But I also wanted to say the following: word to your papa.\
And lastly I wanted to talk about word1..."""
def t(k, t):
ls = len(t)
tmp = {i:len(i) for i in k}
return [{"list_word":i,"string_of_text_after":t[t.find(i) tmp[i]:]} for i in tmp if t.find(i)>0]
from pprint import pprint
pprint(t(keyword_list,string_of_text))
結果:
[{'list_word': 'wordup',
'string_of_text_after': '". But I also wanted to say the following: word to your papa. And lastly I wanted to talk about word1...'},
{'list_word': 'word1', 'string_of_text_after': '...'},
{'list_word': 'anotherWord',
'string_of_text_after': '... and then I\'m going to say something I\'ve been meaning to say "wordup". But I also wanted to say the following: word to your papa. And lastly I wanted to talk about word1...'},
{'list_word': 'word to your papa',
'string_of_text_after': '. And lastly I wanted to talk about word1...'}]
注意力
這段代碼有幾個含義:
- 關鍵字串列必須是獨特的元素......
- 呼叫 t.find(i) 加倍
- 該函式回傳一個串列,該串列必須保存在您的記憶體中,如果您選擇回傳這樣的生成器,則可以解決此問題:
return ({"list_word":i,"string_of_text_after":t[t.find(i) tmp[i]:]} for i in tmp if t.find(i)>0) 并在 where und when 呼叫它需要。
祝你好運 !:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432752.html
上一篇:計算完成時更新for回圈內的輸出
下一篇:函式不會回圈
