テキストクリーナー
テキストから余分なスペース、空行、特殊文字、HTMLタグを削除。
テキストクリーナーは、テキストから不要な書式、余分な空白、一般的なジャンクをワンクリックで削除します。PDF、Wordドキュメント、ウェブページ、メールからテキストをコピーすると、余分な改行、連続するスペース、見えないUnicode文字、コードを壊すスマートクォート、&や のようなHTMLエンティティが含まれることがよくあります。
必要なクリーニング操作を選択してCleanをクリックします。利用可能な操作には、余分な空白と空白行の削除、先頭と末尾のスペースのトリム、複数スペースの1つへの折り畳み、スマート/カーリークォートをストレートクォートへの変換、HTMLタグの削除、HTMLエンティティのデコード、印刷不可文字の削除などがあります。
テキストクリーニングはデータ処理パイプラインの一般的な最初のステップです。テキストデータをデータベース、機械学習モデル、APIにインポートする際、予期しない空白や特殊文字は解析エラーの頻繁な原因となります。
よくある質問
コード実装
import re
import unicodedata
def remove_control_chars(text: str) -> str:
"""Remove non-printable control characters (keep tab, newline, carriage return)."""
return "".join(
ch for ch in text
if unicodedata.category(ch) not in ("Cc", "Cf") or ch in ("\t", "\n", "\r")
)
def normalize_line_endings(text: str, style: str = "lf") -> str:
"""Normalize line endings to LF (Unix) or CRLF (Windows)."""
text = text.replace("\r\n", "\n").replace("\r", "\n")
if style == "crlf":
text = text.replace("\n", "\r\n")
return text
def collapse_whitespace(text: str) -> str:
"""Replace multiple consecutive spaces/tabs on each line with a single space."""
return "\n".join(re.sub(r"[ \t]+", " ", line) for line in text.splitlines())
def trim_lines(text: str) -> str:
"""Strip leading and trailing whitespace from each line."""
return "\n".join(line.strip() for line in text.splitlines())
def remove_blank_lines(text: str) -> str:
"""Collapse multiple consecutive blank lines into one."""
return re.sub(r"\n{3,}", "\n\n", text)
def clean_text(text: str,
control_chars: bool = True,
normalize_endings: bool = True,
collapse_spaces: bool = True,
trim: bool = True,
blank_lines: bool = True) -> str:
"""Run all cleaning steps in sequence."""
if control_chars:
text = remove_control_chars(text)
if normalize_endings:
text = normalize_line_endings(text)
if collapse_spaces:
text = collapse_whitespace(text)
if trim:
text = trim_lines(text)
if blank_lines:
text = remove_blank_lines(text)
return text
sample = " Hello\t world! \n\n\nExtra blank lines \n\x00Null byte here "
print(repr(clean_text(sample)))
# 'Hello world!\n\nExtra blank lines\nNull byte here'Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.