列表与字典:文本数据存哪?
Lists & Dicts: Storing Text Data
文本分析 90% 的数据,要么存列表(一篇文章一行),要么存字典({词: 频次})。这两个结构不熟,后面的 LDA、词云全都跑不起来。
1. 列表 list — 存一串文本
comments = [
"这款手机真不错,拍照很清晰",
"物流太慢了,等了 3 天",
"客服态度很好,五星好评",
"屏幕有点黄,不知道是不是通病"
]
print(len(comments)) # 4 条评论
print(comments[0]) # 第一条
2. 列表的 4 个高频操作
comments.append('新评论') # 末尾加一条
comments.pop() # 删最后一条
comments.remove('物流太慢了,等了 3 天') # 按值删
for c in comments: # 遍历
print(len(c), c[:10])
# 列表推导式(必会)
lengths = [len(c) for c in comments]
print(lengths) # [16, 11, 11, 14]
3. 字典 dict — 存"词 → 频次"
词频统计、词云、LDA 词分布,几乎全用 dict。
word_count = {'手机': 12, '物流': 8, '客服': 5}
word_count['屏幕'] = 3 # 加一个
print(word_count['手机']) # 12
print('价格' in word_count) # False
# 遍历字典
for word, cnt in word_count.items():
print(f"{word}: {cnt} 次")
4. 实战:统计 100 条评论的词频 Top 10
import jieba
from collections import Counter
comments = [...] # 100 条评论
# 1. 全部切词
all_words = []
for c in comments:
words = jieba.lcut(c)
all_words.extend(words) # 把每条的词都加进总列表
# 2. 统计频次
counter = Counter(all_words)
# 3. 取 Top 10
top10 = counter.most_common(10)
for word, cnt in top10:
print(f"{word:8s} {cnt} 次")
进阶技巧:
Counter 是 Python 标准库 collections 里的,专门用来计数,比手写字典 d[word] = d.get(word, 0) + 1 快 10 倍。
5. 嵌套:列表套字典(评论数据库)
# 真实项目的存储结构
reviews = [
{'id': 1, 'text': '手机不错', 'score': 5, 'label': 'pos'},
{'id': 2, 'text': '物流太慢', 'score': 2, 'label': 'neg'},
]
# 取所有正面评论
pos = [r for r in reviews if r['label'] == 'pos']
# 算平均分
avg = sum(r['score'] for r in reviews) / len(reviews)
下一节,我们把这一百条评论从 txt/csv 文件里读进来,完成"从文件到分析"的全流程。