





















Given a mapping from keywords to tags and a user review, replace the keywords in the review with the format [<tag>]{<keyword>}. For example:
Given mapping:
{
"san": "person",
"francisco": "person",
"san francisco": "city",
"Airbnb": "business",
"city": "location",
}
User review:
"I travelled to San Francisco for work and stayed at Airbnb.
I really loved the city and the home where I stayed.
I stayed with San and Francisco.
They both were really good and san's hospitality was outstanding."
Expected output:
"I travelled to [city]{San Francisco} for work and stayed at [business]{Airbnb}.
I really loved the [location]{city} and the home where I stayed.
I stayed with [person]{San} and [person]{Francisco}.
They both were really good and [person]{san}'s hospitality was outstanding."
Implement a function to achieve the above functionality.
1 def tag_keywords(mapping, review): 2 # Sort keywords by length (longest first) to ensure greedy matching 3 # We also lowercase them to make searching easier 4 sorted_keywords = sorted(mapping.keys(), key=len, reverse=True) 5 6 result = [] 7 i = 0 8 n = len(review) 9 10 while i < n: 11 match_found = False 12 13 for keyword in sorted_keywords: 14 k_len = len(keyword) 15 16 # Check if the substring matches the keyword (case-insensitive) 17 if review[i : i + k_len].lower() == keyword.lower(): 18 19 # Check Word Boundaries 20 # 1. Check character before 21 prev_char_ok = (i == 0) or not review[i - 1].isalnum() 22 23 # 2. Check character after 24 next_char_idx = i + k_len 25 next_char_ok = (next_char_idx == n) or not review[next_char_idx].isalnum() 26 27 if prev_char_ok and next_char_ok: 28 # Retrieve the tag and the original text from the review 29 tag = mapping[keyword] 30 original_text = review[i : i + k_len] 31 32 # Append formatted string 33 result.append(f"[{tag}]{{{original_text}}}") 34 35 # Advance the index by the length of the keyword 36 i += k_len 37 match_found = True 38 break 39 40 # If no keyword matched at this position, move forward 1 character 41 if not match_found: 42 result.append(review[i]) 43 i += 1 44 45 return "".join(result) 46 47 # --- Test Case --- 48 mapping = { 49 "san": "person", 50 "francisco": "person", 51 "san francisco": "city", 52 "Airbnb": "business", 53 "city": "location", 54 } 55 56 review = ( 57 "I travelled to San Francisco for work and stayed at Airbnb. " 58 "I really loved the city and the home where I stayed. " 59 "I stayed with San and Francisco. " 60 "They both were really good and san's hospitality was outstanding." 61 ) 62 63 output = tag_keywords(mapping, review) 64 print(output)
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。