← 返回教程目录
第 1 章 · 第 3 节 Python 基础

文件读写:从 txt/csv 读语料

File I/O: Loading Corpus from txt/csv

真实项目里,语料不会写死在代码里 — 而是从 .txt.csv、数据库里读。这一节搞定 3 种最常见格式。

1. 读 txt(每行一条评论)

# 写法 1:一次性读完


with open('comments.txt', 'r', encoding='utf-8') as f:


    lines = f.read().splitlines()  # ['第一行', '第二行', ...]





# 写法 2:逐行读(文件大时省内存)


with open('comments.txt', 'r', encoding='utf-8') as f:


    for line in f:


        line = line.strip()


        if line:  # 跳过空行


            print(line)
关键:encoding='utf-8' 必须写!不写的话 Windows 默认是 gbk,中文会乱码报错。

2. 读 csv(带表头的表格)

用标准库 csvpandas(强烈推荐)。

# 写法 1:标准库 csv


import csv


with open('reviews.csv', 'r', encoding='utf-8') as f:


    reader = csv.DictReader(f)


    for row in reader:


        print(row['id'], row['text'], row['score'])





# 写法 2:pandas(必学,后续教程都靠它)


import pandas as pd


df = pd.read_csv('reviews.csv')


print(df.head())           # 打印前 5 行


print(df['text'].tolist()) # 取出 text 列转列表


print(len(df))             # 总行数

3. 写结果到 csv(导出分析结果)

import pandas as pd





results = [


    {'word': '手机', 'count': 120, 'ratio': 0.24},


    {'word': '物流', 'count': 80,  'ratio': 0.16},


]


df = pd.DataFrame(results)


df.to_csv('word_freq.csv', index=False, encoding='utf-8-sig')


# encoding='utf-8-sig' 让 Excel 打开不乱码

4. 读 json(API 返回值、配置文件)

import json





# 写


config = {'stopwords': ['的', '了', '是'], 'min_freq': 5}


with open('config.json', 'w', encoding='utf-8') as f:


    json.dump(config, f, ensure_ascii=False, indent=2)





# 读


with open('config.json', 'r', encoding='utf-8') as f:


    cfg = json.load(f)


print(cfg['stopwords'])

5. 实战:从 5 万条评论 csv 读出后,过滤长度 < 5 的短评

import pandas as pd





df = pd.read_csv('comments_50k.csv')


print(f"原始: {len(df)} 条")





# 过滤:评论长度 >= 5 字


df = df[df['text'].str.len() >= 5]


print(f"过滤后: {len(df)} 条")





# 存回


df.to_csv('comments_filtered.csv', index=False, encoding='utf-8-sig')

至此,Python 文本分析的"三件套"(字符串 + 列表字典 + 文件 IO)就齐了。下一章开始实战,先学最常用的情感分析

读 5 万条评论太慢?用我们的数据预处理软件,内置并行加速

配套软件内置案例数据 + 模板,导入即出图,无需写代码

查看淘宝软件 →