[英]Efficiently replacing compound words in a tokenized array of strings. Python
在字符串數組中替換復合詞的最有效方法是什么。
text = ['San', 'Francisco', 'is', 'foggy', '.','Viva', 'Las', 'Vegas','.']
replacements = {'san_francisco':['San Francisco'],
'las_vegas': ['Las Vegas'],
}
text2= ' '.join(text)
for key, value in replacements.items():
text2=text2.replace(value[0],key)
final=text2.split(' ')
print(final)
因此,此方法將重建整個字符串,遍歷字典並替換文本。 崇高文字表示這需要0.2秒。 有沒有更有效的方法可以做到這一點?
我尚未在更大的數據集上對此進行分析,但這可能更有效。 解決方案中的許多“繁重工作”都是通過replace
方法完成的,因此哪種方法更有效,在很大程度上取決於cPython replace
方法的優化程度(即,他們可能會使用一些巧妙的技巧使其運行得非常快) 。
text = ['San', 'Francisco', 'is', 'foggy', '.','Viva', 'Las', 'Vegas','.', "wild", "wild", "west"]
replacements = {
'San': {'Francisco': 'san_francisco'},
'Las': {'Vegas': 'las_vegas'},
'wild': {'wild': {'west': 'wild_wild_west'}}
}
for i in range(0, len(text)-1):
if text[i] is None:
continue
replacement_value = replacements.get(text[i])
if replacement_value is None:.
continue
number_of_items_to_delete = 0
while isinstance(replacement_value, dict):
number_of_items_to_delete += 1
replacement_value = replacement_value.get(text[i + number_of_items_to_delete])
text[i] = replacement_value
for j in range(i+1, i+1 + number_of_items_to_delete):
text[j] = None
text = [n for n in text if n is not None]
print (text)
現在,我們為查詢表使用嵌套字典。 請注意,我已經“翻轉”了查詢表,以便鍵來自單詞列表中的值,我們希望在表中查找要替換的值。
該算法可以描述如下:
None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.