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

推荐订阅源

S
Secure Thoughts
P
Privacy International News Feed
T
Tenable Blog
L
Lohrmann on Cybersecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
S
Securelist
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Vercel News
Vercel News
Cyberwarzone
Cyberwarzone
月光博客
月光博客
T
The Blog of Author Tim Ferriss
Scott Helme
Scott Helme
爱范儿
爱范儿
Stack Overflow Blog
Stack Overflow Blog
C
Cisco Blogs
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
阮一峰的网络日志
阮一峰的网络日志
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Security Latest
Security Latest
Blog — PlanetScale
Blog — PlanetScale
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
博客园 - 三生石上(FineUI控件)
I
InfoQ
Spread Privacy
Spread Privacy
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
C
CERT Recently Published Vulnerability Notes
A
About on SuperTechFans
博客园_首页
Engineering at Meta
Engineering at Meta
Project Zero
Project Zero
Latest news
Latest news

博客园 - 北叶青藤

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)