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

推荐订阅源

IT之家
IT之家
博客园 - 聂微东
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
博客园 - 司徒正美
爱范儿
爱范儿
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
博客园 - 【当耐特】
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
人人都是产品经理
人人都是产品经理
V
V2EX

博客园 - 北叶青藤

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)