文本计数器
你将构建什么
Python script 那个读取 multi-行文本从 用户, 然后 prints 数字的 characters, words, and 行. miniature version 的 word-数量 tool.
学习目标
- Use len() 到数量 characters and 行
- Use str.拆分() 到拆分文本到 words
- 读取 multi-行输入使用 sentinel 循环
- 格式 summary report 使用 f-字符串
前置要求
- 字符串 and 字符串方法
- 列表 and len()
- for or 虽然循环
步骤
- 1
读取 multi-行输入
读取行 从用户直到它们类型 sentinel 行 ("END"). 虽然循环使用 break 条件是 标准方式到 读取 unknown-长度输入.
代码lines = [] print("Enter text. Type END on its own line to finish.") while True: line = input() if line == "END": break lines.append(line)预期结果
script 读取行 直到用户类型 END, 存储它们 in 列表.
提示
In 真实 script 你会 读取从 file; 这里我们 use 输入 for simplicity.
- 2
连接行 and 数量 characters
连接行 到 one 字符串使用 newline separators, 然后 use len() 到数量 characters. len() on 字符串返回数字的 characters 包含空间.
代码text = "\n".join(lines) char_count = len(text)预期结果
char_count 持有总计数字的 characters in 合并文本.
- 3
数量 words and 行
Use 文本.拆分() 到拆分 on 任何 whitespace and len() 到数量 resulting words. 行数量是 只是 len(行). 拆分() 使用否 实参 handles 多个空间 and newlines.
代码words = text.split() word_count = len(words) line_count = len(lines)预期结果
word_count and line_count 持有 two remaining 数量.
- 4
Print summary
Print 所有 three 数量使用 f-字符串. 清晰 summary 是输出用户 actually 想要从 counting tool.
代码print(f"Characters: {char_count}") print(f"Words: {word_count}") print(f"Lines: {line_count}")预期结果
Three 行 showing character, word, and 行数量.
- 5
添加输入验证与异常处理
在主函数中添加 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)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
自己动手试试
lines = []
print("Enter text. Type END on its own line to finish.")
# TODO: read lines, join, count chars/words/lines, print summarylines = []
print("Enter text. Type END on its own line to finish.")
while True:
line = input()
if line == "END":
break
lines.append(line)
text = "\n".join(lines)
char_count = len(text)
words = text.split()
word_count = len(words)
line_count = len(lines)
print(f"Characters: {char_count}")
print(f"Words: {word_count}")
print(f"Lines: {line_count}")你学到了什么
你组合 sentinel 输入循环, 字符串合并, 拆分, and len() 到构建文本 analysis tool — 相同字符串-处理模式 used 通过 word 计数器, log parsers, and 数据 scripts.
相关资源
相关练习
- 字符串 Predict
Predict result 的拆分, 连接, and len on 字符串.
- 列表 MCQ
测验 on 列表操作如 append and len.
相关工具
- Word 计数器
Compare 你的 Python 输出使用浏览器-based word 计数器.
相关速查表
- Python Cheatsheet
字符串方法, 列表, and 循环语法引用.
相关参考文档
- Python 字符串方法
完整字符串方法引用.
- Python 列表方法
完整列表方法引用.
相关错误
- 索引错误
Accessing 无效索引.
- Attribute 错误
Calling nonexistent 方法.
相关术语
- 字符串
文本数据 in code.
- 列表
有序可变集合.
- Dictionary
键-值映射.
- Python
Python language 概念.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
- 字符串
文本数据 in code.
- 列表
有序可变集合.
- Dictionary
键-值映射.
- Python
Python language 概念.
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- 索引错误
Accessing 无效索引.
- Attribute 错误
Calling nonexistent 方法.