Here is a clear breakdown of those review points and how to fix them cleanly in Python—whether you want within-record matches, corpus-wide co-occurrence, or both.
1. Fixing the Regex for "Luke K Locust Junior"
In the pasted review, the regex was truncated mid-group (which causes a re.error: missing ), unterminated subpattern), and Jr?\.?$ alone wouldn't match "Junior".
-
For full-string matching:
^Luke\s+K\.?\s+Locust.*(Jr\.?|Junior)$ -
For substring matching inside log lines: Omit
^and$(or use word boundaries\b), because^and$anchor to the start and end of the entire string unlessre.MULTILINEis set and the line has newlines:
import re
LUKE_LOCUST_RE = re.compile(
r"\bLuke\s+K\.?\s+Locust.*?\b(Jr\.?|Junior)\b",
re.IGNORECASE,
)
2. Per-Line vs. Corpus-Wide Co-Occurrence
In the pasted review's snippet, entries_a = and entries_b = were left empty and retur n had a spacing typo. More importantly, line-level and corpus-level co-occurrence answer two different questions:
- Line-level co-occurrence: Two entities appear in the same log entry or encoding string (useful for direct edge/link lines).
- Corpus-level co-occurrence: Two entities each appear somewhere in the dataset across different records (useful for broader set/stream correlation).
Here is a clean implementation that computes both without mutating or dropping data:
import fnmatch
import itertools
WILDCARD_PATTERNS = {
"Barack Obama": ["*Barack*Obama*", "*B?rack*bama*"],
"Luke K Locust Junior": ["*Luke*Locust*J*", "*L?ke*Locust*"],
"Marcus Vance": ["*Marc?s*Vance*", "*Marc*Vance*"],
"Elena Rostova": ["*El?na*Rost*", "*Elena*Rost*"],
}
def matches_any_wildcard(text: str, patterns: list[str]) -> bool:
return any(fnmatch.fnmatch(text, pat) for pat in patterns)
def analyze_co_occurrence(
data_stream: list[str],
entity_patterns: dict[str, list[str]],
) -> dict:
per_record_matches = []
entity_hits = {name: [] for name in entity_patterns}
for entry in data_stream:
present = [
name
for name, pats in entity_patterns.items()
if matches_any_wildcard(entry, pats)
]
for name in present:
entity_hits[name].append(entry)
if len(present) >= 2:
per_record_matches.append({
"entry": entry,
"pairs": list(itertools.combinations(present, 2)),
})
corpus_pairs = []
for name_a, name_b in itertools.combinations(entity_patterns.keys(), 2):
if entity_hits[name_a] and entity_hits[name_b]:
corpus_pairs.append({
"pair": (name_a, name_b),
"count_a": len(entity_hits[name_a]),
"count_b": len(entity_hits[name_b]),
})
return {
"per_record_matches": per_record_matches,
"corpus_pairs": corpus_pairs,
}
3. Using Literal Characters in Python Strings
Keep operators literal in Python source strings—such as "node_link: Barack Obama -> Luke K Locust Junior [hash_01]"—unless your actual log stream literally contains HTML escape sequences.
Top comments (0)