Last active
May 19, 2020 01:52
-
-
Save kzinmr/1a916232909f41594838a025283f68ef to your computer and use it in GitHub Desktop.
Generate window contexts and count cooccurence within them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import List | |
| from itertools import tee, combinations | |
| from collections import Counter | |
| # def count_cooccurrence_in_window(context_window, delimiter=' '): | |
| # return Counter([delimiter.join(bi) for bi in combinations(context_window, 2)]) | |
| def window_cooccurrence(sentence: List[str], window: int = 5) -> Counter: | |
| """ Count cooccurrence in window in given sentence | |
| 1. enumerate contexts in window by | |
| [list(it)[i:i + window] for i, it in enumerate(tee(sentence, num))]: | |
| ['A','B','C','D', 'E', 'F', 'G'], 4 -> | |
| [['A', 'B', 'C', 'D'], | |
| ['B', 'C', 'D', 'E'], | |
| ['C', 'D', 'E', 'F'], | |
| ['D', 'E', 'F', 'G']] | |
| 2. generete and count cooccurrence within the each context above by | |
| [pair for pair in combinations(list(it)[i:i + window], 2)]: | |
| ['A', 'B', 'C', 'D'] -> | |
| [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')] | |
| """ | |
| assert len(sentence) >= window | |
| num = len(sentence) - window + 1 | |
| return Counter([ | |
| pair | |
| for i, it in enumerate(tee(sentence, num)) | |
| for pair in combinations(list(it)[i:i + window], 2) | |
| ]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.