文本 Processor
你将构建什么
Python script 使用函数到 clean whitespace, 数量 word frequency, 查找 and replace, and convert 情况 — mini 文本 toolkit.
学习目标
- Use 字符串方法 (strip, 拆分, replace, lower) 到 clean 文本
- 数量 word frequency 使用 dictionary
- 构建 reusable 函数使用清晰参数
- 格式 readable summary report
前置要求
- 字符串 and 字符串方法
- Dictionaries
- 函数
步骤
- 1
编写文本 cleaning 函数
定义 clean_text(文本) 那个 strips leading/trailing whitespace, collapses 多个空间到 one, and converts 到 lowercase. 这个 normalizes 文本 for consistent 处理.
代码def clean_text(text): import re text = text.strip().lower() text = re.sub(r'\s+', ' ', text) return text预期结果
clean_text(' Hello 世界 ') 返回 'hello 世界'.
- 2
数量 word frequency
定义 word_frequency(文本) 那个拆分文本到 words and 数量每个 word using dictionary. 返回 dict 排序通过 frequency (highest 首先).
代码def word_frequency(text): words = text.split() freq = {} for word in words: freq[word] = freq.get(word, 0) + 1 return dict(sorted(freq.items(), key=lambda x: x[1], reverse=True))预期结果
word_frequency(' b c ') 返回 {'': 3, 'b': 1, 'c': 1}.
- 3
构建 report 函数
定义 report(文本) 那个 cleans 文本, 数量 words and characters, 查找顶部 3 words, and prints 格式化 summary.
代码def report(text): cleaned = clean_text(text) freq = word_frequency(cleaned) print(f"Characters: {len(cleaned)}") print(f"Unique words: {len(freq)}") print("Top 3 words:") for word, count in list(freq.items())[:3]: print(f" {word}: {count}")预期结果
Calling report on sample 文本 prints character 数量, 唯一 word 数量, and 顶部 3 words.
- 4
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
- 5
编写单元测试
使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。
代码import unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()预期结果
运行 python test.py 后输出 OK,三个测试用例全部通过。
自己动手试试
# TODO: define clean_text, word_frequency, and report
# Then test with: report("The quick brown fox jumps over the lazy dog")
import re
def clean_text(text):
text = text.strip().lower()
text = re.sub(r'\s+', ' ', text)
return text
def word_frequency(text):
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return dict(sorted(freq.items(), key=lambda x: x[1], reverse=True))
def report(text):
cleaned = clean_text(text)
freq = word_frequency(cleaned)
print(f"Characters: {len(cleaned)}")
print(f"Unique words: {len(freq)}")
print("Top 3 words:")
for word, count in list(freq.items())[:3]:
print(f" {word}: {count}")
report("The quick brown fox jumps over the lazy dog")你学到了什么
你构建文本处理 toolkit 组合字符串方法, dictionary counting, and 排序 — 相同模式 used in log analysis, 搜索 engines, and NLP 流水线.
相关资源
相关课程
- 字符串
字符串方法 for 文本处理.
- Dictionaries
Counting 使用 dictionaries.
相关练习
- 字符串方法测验
练习字符串方法.
- Predict 字符串拆分
Predict 拆分输出.
相关速查表
- Python Cheatsheet
字符串 and dict 引用.
相关错误
- Attribute 错误
错误字符串方法 names.
- 键错误
Missing dict 键.
相关术语
- 字符串
文本数据.
- Dictionary
键-值映射.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
- 字符串
文本数据.
- Dictionary
键-值映射.
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- Attribute 错误
错误字符串方法 names.
- 键错误
Missing dict 键.