在進行了一些文本處理之后,我得到了一個標記串列和一個句子索引串列,每個標記一個。現在我想將標記重新組合成句子。我用過 Numpy,但我覺得有更好/更快/更 numpy-ish 的方式來做到這一點......沒有 for 回圈。未來可能會超過兩句話。
import numpy as np
all_tokens = np.array(['I', 'spent', 'a', 'lot', 'of', 'time', ',', 'money', ',', 'and', 'effort', 'childproofing', 'my', 'house', '.', 'However', ',', 'the', 'kids', 'still', 'get', 'in', '.'])
sent_ids = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1])
new_sents = []
for unique_sent_id in np.unique(sent_ids):
sent_tokens = all_tokens[sent_ids == unique_sent_id].tolist()
new_sents.append(' '.join(sent_tokens))
結果:[“我花了很多時間、金錢和精力來保護我的房子。”,“但是,孩子們還是進去了。”]
uj5u.com熱心網友回復:
假設sent_ids是有序的,您可以找出sent_id發生變化的位置,然后根據該位置拆分令牌:
list(map(" ".join, np.split(all_tokens, np.flatnonzero(np.diff(sent_ids) != 0) 1)))
# ['I spent a lot of time , money , and effort childproofing my house .', 'However , the kids still get in .']
uj5u.com熱心網友回復:
在我看來,sent_ids == unique_sent_id在每次迭代中使用可能意味著您的程式每次都必須遍歷整個可能非常長的 sent_ids 陣列。
不確定這是否是您想象的那樣,但我會這樣做以確保只發生一次迭代,因為您只從左到右遍歷兩個陣列一次:
import numpy as np
all_tokens = np.array(
['I', 'spent', 'a', 'lot', 'of', 'time', ',', 'money', ',', 'and', 'effort', 'childproofing', 'my', 'house', '.',
'However', ',', 'the', 'kids', 'still', 'get', 'in', '.'])
sent_ids = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1])
new_sents = []
current_sent_id = -1
for token, sent_id in zip(all_tokens, sent_ids):
if sent_id != current_sent_id:
new_sents.append(token)
current_sent_id = sent_id
else:
new_sents[-1] = " " token
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433830.html
