合并重复文档可以通过以下几种方法实现:
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 osfrom docx import Documentfrom 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())
请根据你的具体需求选择合适的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/36869.html