数据柜检查
Hoppy 站在数据柜前,桌上同时摊开了三样东西:一张自由书写的线索便签、一份字段整齐的守柜记录、还有一张按行列排好的库存表。
这一章的 checkpoint 不想考你背多少术语,而是想确认一个更真实的能力:当不同形状的信息摆在一起时,你能不能判断哪种格式更适合它,并且从每种格式里拿到一点有用内容。
不是所有信息都该塞进同一种格式
普通文本适合自由描述;JSON 适合一条有名字字段的记录;CSV 适合重复多行的表格。真正的数据整理,不只是会“读”,还包括会判断什么时候该用哪种形状。
camp_note = "Lanterns ready at dusk."
keeper_record = {"guide": "Pip", "room": "Moss Shelf"}
stock_sheet = "item_name,count
fern rope,2
moon lamp,1"
note_format = "text"
record_format = "json"
sheet_format = "csv"
print(note_format, record_format, sheet_format)
这个示例只是帮你重新摆正三种格式的直觉,不是今天 starter 的完整答案。真正的任务里,你会在三份真实小样本上同时做“选择格式 + 取一点细节”这两个动作。
今天的任务:为三种信息选格式,再做一个小整理
starter 已经帮你读好了三份样本:cabinet_note.txt、guard_record.json、stock_table.csv。你要先判断它们分别最适合哪种格式标签,再从里面各取一个小细节,最后收成一份 cabinet_plan。
运行 starter,先看:便签是自由文本,守柜记录是单条有字段的结构,库存表是按行和列重复展开的表。
把 clue_note_format、guard_record_format、stock_table_format 设成最合适的格式标签。
从便签里拿出第一行 note_first_line,从 JSON 里拿出 keeper_name,再从 CSV 第一条数据记录里拿出 first_item_name。
用这些选择和细节构造 cabinet_plan。这就是一次很轻的综合整理:会比较格式,也会做一点读取和收束。
这一课只检查 Chapter 4 的基础判断与轻量处理:文本、JSON、CSV 三种格式的用途对比,以及从每种格式中拿一点简单信息。我们不做大型项目,也不进入 API 或本机文件系统话题。
参考答案点击展开点击收起
import json
with open("cabinet_note.txt", "r", encoding="utf-8") as file:
note_text = file.read().strip()
with open("guard_record.json", "r", encoding="utf-8") as file:
guard_record = json.load(file)
with open("stock_table.csv", "r", encoding="utf-8") as file:
stock_csv_text = file.read().strip()
print("Note text:")
print(note_text)
print("Guard record:", guard_record)
print("Stock table:")
print(stock_csv_text)
stock_rows = stock_csv_text.splitlines()
clue_note_format = "text"
guard_record_format = "json"
stock_table_format = "csv"
note_first_line = note_text.splitlines()[0]
keeper_name = guard_record["keeper_name"]
first_item_name = stock_rows[1].split(",")[0]
cabinet_plan = {
"clue_note_format": clue_note_format,
"guard_record_format": guard_record_format,
"stock_table_format": stock_table_format,
"note_first_line": note_first_line,
"keeper_name": keeper_name,
"first_item_name": first_item_name
}
print("Clue note format:", clue_note_format)
print("Guard record format:", guard_record_format)
print("Stock table format:", stock_table_format)
print("Note first line:", note_first_line)
print("Keeper name:", keeper_name)
print("First item name:", first_item_name)
print("Cabinet plan:", cabinet_plan)高级技巧想更进一步?点击展开点击收起
这节 checkpoint 最想确认的不是“你记住了哪几个名词”,而是你开始具备了一点结构选择意识:自由文本、单条记录、重复表格,其实适合不同的表达方式。
到这里,Chapter 4 的基础形状就收束完了。下一章如果继续做,就会开始进入更真实的文本侦探场景。