utility2026-07-253 分钟阅读
什么是文本去重
文本去重是移除文本中重复的行、段落或内容的过程。它可以帮助清理数据、减少冗余、提高文本质量。
去重类型
| 类型 | 说明 | 示例 |
|------|------|------|
| 精确去重 | 完全相同的行 | abc + abc → abc |
| 忽略大小写去重 | 忽略大小写差异 | ABC + abc → abc |
| 忽略空白去重 | 忽略首尾空白 | abc + abc → abc |
| 模糊去重 | 相似度超过阈值 | hello + helo → hello |
| 段落去重 | 移除重复段落 | 相同段落只保留一个 |
去重算法
精确去重(Set 去重):
输入: ["a", "b", "a", "c", "b"]
Set: {"a", "b", "c"}
输出: ["a", "b", "c"]
保留首次出现:
输入: ["c", "a", "b", "a", "c"]
输出: ["c", "a", "b"] ← 保留第一次出现的顺序
为什么需要文本去重
- 数据清洗:清理爬虫或 API 获取的重复数据
- 日志分析:移除重复日志行,只保留唯一条目
- SEO 内容:检测和移除重复内容
- 邮件列表:清理重复的联系人邮箱
- 代码审查:检测重复代码行
- 文本编辑:清理复制粘贴产生的重复
如何使用在线工具
使用 DevToolkit Pro 的 文本去重工具:
- 粘贴或输入文本
- 选择去重模式(精确/忽略大小写/模糊)
- 选择排序方式(保持原序/字母排序/频率排序)
- 实时预览去重结果
- 一键复制去重后的文本
代码中的去重
JavaScript
// 精确去重(保持顺序)
function dedupeExact(text) {
const lines = text.split('\n');
const seen = new Set();
return lines.filter(line => {
if (seen.has(line)) return false;
seen.add(line);
return true;
}).join('\n');
}
// 忽略大小写去重
function dedupeIgnoreCase(text) {
const lines = text.split('\n');
const seen = new Set();
return lines.filter(line => {
const lower = line.toLowerCase();
if (seen.has(lower)) return false;
seen.add(lower);
return true;
}).join('\n');
}
// 模糊去重(基于相似度)
function dedupeFuzzy(text, threshold = 0.85) {
const lines = text.split('\n');
const unique = [];
for (const line of lines) {
if (!unique.some(u => similarity(u, line) >= threshold)) {
unique.push(line);
}
}
return unique.join('\n');
}
// 计算相似度(Jaccard 系数)
function similarity(a, b) {
const setA = new Set(a.split(''));
const setB = new Set(b.split(''));
const intersection = new Set([...setA].filter(x => setB.has(x)));
const union = new Set([...setA, ...setB]);
return intersection.size / union.size;
}
Python
from collections import OrderedDict
def dedupe_exact(text):
"""精确去重,保持顺序"""
lines = text.split('\n')
return '\n'.join(OrderedDict.fromkeys(lines))
def dedupe_ignore_case(text):
"""忽略大小写去重"""
lines = text.split('\n')
seen = set()
result = []
for line in lines:
lower = line.lower()
if lower not in seen:
seen.add(lower)
result.append(line)
return '\n'.join(result)
def dedupe_fuzzy(text, threshold=0.85):
"""模糊去重"""
from difflib import SequenceMatcher
lines = text.split('\n')
unique = []
for line in lines:
if not any(SequenceMatcher(None, u, line).ratio() >= threshold for u in unique):
unique.append(line)
return '\n'.join(unique)
FAQ
去重后顺序会变吗?
默认保留原始顺序(首次出现的顺序)。也可以选择按字母排序或按频率排序(出现次数多的在前)。
如何处理空行?
可以选择:1) 保留空行只去重非空行;2) 将连续空行合并为一个;3) 完全移除所有空行。根据你的需求选择。
模糊去重的阈值怎么设置?
阈值 0-1 之间,越接近 1 要求越严格。推荐:0.85-0.9(宽松)用于清理轻微变体,0.95+(严格)用于只去除几乎完全相同的行。
本文由 DevToolkit Pro 提供。更多开发者工具请访问 首页。