Skip to content

Instantly share code, notes, and snippets.

@korakot
Last active January 20, 2023 02:36
Show Gist options
  • Select an option

  • Save korakot/f91d318102291c1427dcaa582c712fd0 to your computer and use it in GitHub Desktop.

Select an option

Save korakot/f91d318102291c1427dcaa582c712fd0 to your computer and use it in GitHub Desktop.
Strip line to get only context around a word
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]
# 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