-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregular-expression.py
More file actions
36 lines (29 loc) · 1.55 KB
/
Copy pathregular-expression.py
File metadata and controls
36 lines (29 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Based on code from LLMs-from-scratch by Sebastian Raschka (https://github.com/rasbt/LLMs-from-scratch)
# Licensed under the Apache License, Version 2.0
import re
# --------------------------------------------------
# 1. re.split の例(テキストのトークン分割)
# --------------------------------------------------
text1 = "Hello, world. Is this-- a test?"
result1 = re.split(r'([,.:;?_!"()\']|--|\s)', text1)
result1 = [item.strip() for item in result1 if item.strip()]
print("--- 1. re.split ---")
print(result1)
print("\n" + "=" * 40 + "\n")
# --------------------------------------------------
# 2. re.sub の例(decode処理:記号前の不要なスペース削除)
# --------------------------------------------------
# トークンIDのリストを " ".join() で結合した直後の状態を想定
text2 = "Hello , world ! Is this ( a test ) ?"
# 【パターンの解説】
# r'\s+([,.?!"()\'])'
# - \s+ : 1つ以上の空白文字(スペースやタブなど)
# - ([,.?!"()\']) : キャプチャグループ1。指定した約物・記号(, . ? ! " ( ) ')にマッチ
#
# 【置換文字列の解説】
# r'\1' : マッチした部分全体(「空白+記号」)を「グループ1(記号のみ)」で置き換える
# : これにより、記号の直前にあった空白だけが削除される
result2 = re.sub(r'\s+([,.?!"()\'])', r'\1', text2)
print("--- 2. re.sub (decode pattern) ---")
print("Before:", text2)
print("After :", result2)