python - 如何检查倒序字符串元组并将它们从 python 文件中删除?
问题描述
我想从我的大文本文件(>16M 行)中删除倒序字符串元组。
例如,如果我的文件中有以下两行:
352_0F, 352_1F, 0.913
352_1F, 352_0F, 0.913
预期的输出将保留这些行中的任何一条(而不是两者):
352_0F, 352_1F, 0.913
col3
仅供参考:对于元组及其倒序元组,第三列将是相同的。
我尝试了以下代码,但它没有按预期工作。
from collections import defaultdict
data = defaultdict(list)
with open("OUTPUT.txt","w") as output:
for fileName in ["Large_INPUT.txt"]:
with open(fileName,'r') as file1:
for line in file1:
col1,col2,value = line.split(",")
if (col1,col2) not in data:
if (col2,col1) not in data:
data[(col1,col2,value)]
output.write(f"{col1},{col2} {value}\n")
有人可以帮我吗?
解决方案
看到您的代码有一个单个文件的列表,我假设您正在将其概括为与多个文件一起使用。在那种情况下,您没有提及某些内容,您是否希望组合在文件中持续存在?你已经接近你的实施了。除了使用字典来获得 O(1) 搜索,您还可以使用更简单的结构、set 并获得 O(1) 搜索。
持久化文件列表
found_combinations = set()
with open("OUTPUT.txt", "w") as output:
for fileName in ["Large_INPUT.txt"]:
with open(fileName, 'r') as file1:
for line in file1:
cols = [col.strip() for col in line.strip().split(',')]
new_combination = frozenset(cols)
if new_combination not in found_combinations:
found_combinations.add(new_combination)
out = ', '.join(cols) + '\n'
output.write(out)
对文件不持久
with open("OUTPUT.txt", "w") as output:
for fileName in ["Large_INPUT.txt"]:
found_combinations = set()
with open(fileName, 'r') as file1:
for line in file1:
cols = [col.strip() for col in line.strip().split(',')]
new_combination = frozenset(cols)
if new_combination not in found_combinations:
found_combinations.add(new_combination)
out = ', '.join(cols) + '\n'
output.write(out)
请注意,两个版本之间的唯一区别是found_combinations = set()
推荐阅读
- git - 从 SVN 更改为 GIT 需要 GIT 的相关命令
- java - 为什么我需要向 Java 接口添加方法,以便在 Junit 单元测试中访问它?
- git - gitignore:忽略新添加到 .gitignore 的文件
- python - 使用 python selenium 获取文本
- java - 在 JDBC 中使用 unnest(array[someArray]) 发送三个数组的异常
- angular - 如何在 angular2-markdown 的降价中包含降价
- ios - 如何从传输对象的列表类型中获取数据?(RealmSwift)
- python-3.x - 根据每行中的字符串对数据进行分类
- asp.net-mvc - 更改引导程序时导航栏无法正确显示
- javascript - 如何从 firebase 检索和显示与特定用户配置文件相关的数据