合并重复文档可以通过以下几种方法实现:
1. 使用Python的`set`和`union`函数合并文本文件:
打开文件并读入内容
with open('file1.txt', 'r') as f1:
lines1 = f1.readlines()
with open('file2.txt', 'r') as f2:
lines2 = f2.readlines()
将文件内容存储在set中,去除重复的行
set1 = set(lines1)
set2 = set(lines2)
使用union函数将两个set合并起来
merged_set = set1.union(set2)
将合并后的set转换为列表
merged_list = list(merged_set)
将合并后的列表写入新文件
with open('merged_file.txt', 'w') as f:
for line in merged_list:
f.write(line)
2. 使用`pandas`按列合并多个文件:
import pandas as pd
读取文件
file = pd.read_csv('pink.csv', encoding='gbk')
file2 = pd.read_csv('pimk2.csv', encoding='gbk')
按列合并文件
file3 = pd.merge(file, file2, how='left', left_on='', right_on='')
3. 使用`python-docx`和`docxcompose`合并多个Word文档:
import os
from docx import Document
from docxcompose.composer import Composer
指定文档路径
original_docx_path = 'path/to/docx/files'
new_docx_path = 'path/to/new/docx'
创建Composer对象
composer = Composer(new_docx_path)
遍历文件夹中的所有docx文件
for filename in os.listdir(original_docx_path):
if filename.endswith('.docx'):
doc = Document(os.path.join(original_docx_path, filename))
将每个文档添加到Composer对象中
composer.append(doc)
保存合并后的文档
composer.save()
4. 使用`pandas`按行合并多个文件,并处理缩进问题:
import pandas as pd
读取文件
df = pd.read_csv('example.txt', sep=' ', header=None)
df = df.astype(str) 将数字转换为字符串
按前两列分组,并合并相同前两列的行
grouped = df.groupby([0, 1])
result = grouped.agg(' | '.join)
将结果保存到新文件
result.to_csv('merged_example.txt', index=False, sep=' ')
5. 合并多个txt文件到一个文件:
定义要合并的txt文件列表
txt_files = ['file1.txt', 'file2.txt', 'file3.txt']
打开要写入的合并文件
with open('merged_file.txt', 'w') as outfile:
遍历每个txt文件
for file in txt_files:
打开每个txt文件
with open(file, 'r') as infile:
将文件内容写入合并文件
outfile.write(infile.read())
请根据你的具体需求选择合适的方法。