惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
有赞技术团队
有赞技术团队
Jina AI
Jina AI
H
Help Net Security
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
MyScale Blog
MyScale Blog
N
Netflix TechBlog - Medium
B
Blog RSS Feed
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
美团技术团队
M
MIT News - Artificial intelligence
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
Keyword Tagging in Reviews with Overlapping Matches
北叶青藤 · 2026-02-25 · via 博客园 - 北叶青藤

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)