Last active
January 20, 2023 02:36
-
-
Save korakot/f91d318102291c1427dcaa582c712fd0 to your computer and use it in GitHub Desktop.
Strip line to get only context around a word
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
| def context(line, word, padding=40): | |
| # หาคำแรก แล้ว pre-40, หาคำสุดท้าย post+40 เอาง่ายๆ แบบนี้ล่ะ | |
| p1 = line.index(word) | |
| p1s = line.rfind(' ', 0, max(0, p1-padding)) | |
| if p1s==-1: | |
| p1s = 0 | |
| p2 = line.rindex(word) | |
| p2s = line.find(' ', min(len(line), p2+padding)) | |
| if p2s == -1: | |
| p2s = len(line) | |
| return line[p1s+1:p2s] |
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
| # accept list of words instead | |
| def context(line, words, padding=40): | |
| p1 = len(line) | |
| for w in words: | |
| p = line.find(w) | |
| if p == -1: continue | |
| p1 = min(p1, p) | |
| p1s = line.rfind(' ', 0, max(0, p1-padding)) | |
| if p1s==-1: | |
| p1s = 0 | |
| p2 = max(line.rfind(w) for w in words) | |
| p2s = line.find(' ', min(len(line), p2+padding)) | |
| if p2s == -1: | |
| p2s = len(line) | |
| return line[p1s+1:p2s] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment