如何修改Python代码实现文本去重合并并按3列字母排序输出?
问题:如何修改Python代码实现文本去重合并后按字母排序并以3列格式输出?
我用以下Python代码实现了a.txt和b.txt两个文本文件的去重合并功能:
# open files a.txt and b.txt and get the content as a list of lines with open('a.txt') as f: a = f.readlines() with open('b.txt') as f: b = f.readlines() # get the string from the list a_str = ''.join(a) b_str = ''.join(b) # get sets of unique words a_set = set(a_str.split(" ")) b_set = set(b_str.split(" ")) # merge sets c_set = a_set.union(b_set) # write to a new file with open('c.txt', 'w') as f: f.write(' '.join(c_set))
该代码可完成去重合并,但我需要将生成的c.txt内容按字母顺序排序,并以3列的格式呈现。
输入示例:
text a:
NewYork London Paris Rome Tokyo Berlin Edinburgh LosAngeles Madrid
text b:
Madrid Cracow Porto Rome Berlin Barcelona Manchester Tokyo Dublin
期望输出的c.txt格式:
Barcelona Berlin Cracow Dublin Edinburgh London LosAngeles Madrid Manchester NewYork Paris Porto Rome Tokyo
请问如何修改代码实现该需求?
解决方案
你需要对原代码做三处核心修改:处理空字符串、排序结果、格式化3列输出,完整代码如下:
# 读取文件内容并合并为单个字符串 def read_file(file_path): with open(file_path) as f: return f.read() content_a = read_file('a.txt') content_b = read_file('b.txt') # 合并内容并分割为单词列表,过滤空字符串(解决多空格分割产生空值的问题) all_words = content_a.split() + content_b.split() # 去重 unique_words = list(set(all_words)) # 按字母顺序排序 sorted_words = sorted(unique_words) # 按3列格式组织输出内容 column_width = 12 # 可根据需求调整列宽 output_lines = [] # 每3个单词为一组 for i in range(0, len(sorted_words), 3): group = sorted_words[i:i+3] # 格式化每组为对齐的列,不足3个的话只显示现有内容 line = ''.join(f'{word:<{column_width}}' for word in group) output_lines.append(line) # 写入结果文件 with open('c.txt', 'w') as f: f.write('\n'.join(output_lines))
关键修改说明:
- 处理空字符串:原代码用
split(" ")会因为原文件的多空格产生大量空字符串,改用无参数的split()会自动按任意空白字符分割,同时忽略空值。 - 排序:用
sorted()函数对去重后的单词列表按字母顺序排序。 - 3列格式化:
- 定义
column_width控制每列的宽度,确保文字对齐; - 按每3个单词为一组遍历排序后的列表;
- 用
f'{word:<{column_width}}'实现左对齐的格式化输出,每组拼接成一行; - 最后将所有行写入文件。
- 定义
运行修改后的代码,生成的c.txt就会符合你期望的排序和3列格式。
内容的提问来源于stack exchange,提问作者batardavelo
相关产品推荐
相关产品推荐

