Python:如何逐行验证输入文件,修复可能的错误,并将清理后的行写入另一个文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:如何逐行验证输入文件,修复可能的错误,并将清理后的行写入另一个文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1689字,纯文字阅读大概需要3分钟。
内容图文
![Python:如何逐行验证输入文件,修复可能的错误,并将清理后的行写入另一个文件?](/upload/InfoBanner/zyjiaocheng/820/618032d70c914a99a2c0981497a73392.jpg)
我在文本文件中的行看起来像这样:
data/processed/10/blueprint-0.png,1915.0,387.0,1933.0,402.0
data/processed/10/blueprint-0.png,3350.0,387.0,3353.0,388.0
1915位置处的数字应始终小于1933位置处的元素,并且387位置处的元素应始终小于402位置处的元素.
不幸的是,情况并非总是如此,因为我的数据并不完全干净.为了解决这个问题,我想创建另一个文件,我只是复制该行,如果它是正确的,并进行必要的调整,如果不是那样将它固定在新文件中(我不想操纵原始文件中的数据) .
我的代码:
path = 'data/faulty.txt'
with open(path ) as f:
with open('data/true_values.txt', 'a') as the_file:
for line in f:
numbers = re.findall(r'\d+', line)
if numbers:
if numbers[2] > numbers[6]:
temp = numbers[2]
numbers[2] = numbers[6]
numbers[6] = temp
if numbers[4] > numbers[8]:
temp = numbers[2]
numbers[2] = numbers[6]
numbers[6] = temp
the_file.write(line)
如何进行更改?我还考虑过使用re.sub但无法使其工作.
解决方法:
没有re的例子:
input_filename = 'full_path_to_my_input_file.txt'
output_filename = 'full_path_to_my_output_file.txt'
with open(output_filename, 'a') as f_out:
with open(input_filename, 'r') as f_in:
for line in f_in:
records = line.strip().split(',')
if float(records[1]) > float(records[3]):
records[1], records[3] = records[3], records[1]
if float(records[2]) > float(records[4]):
records[2], records[4] = records[4], records[2]
f_out.write(','.join(records) + '\n')
输入:
data/processed/10/blueprint-0.png,1915.0,387.0,1933.0,402.0
data/processed/10/blueprint-0.png,3353.0,389.0,3350.0,388.0
data/processed/10/blueprint-0.png,952.0,724.0,1010.0,734.0
输出:
data/processed/10/blueprint-0.png,1915.0,387.0,1933.0,402.0
data/processed/10/blueprint-0.png,3350.0,388.0,3353.0,389.0 ## swapped !!
data/processed/10/blueprint-0.png,952.0,724.0,1010.0,734.0
内容总结
以上是互联网集市为您收集整理的Python:如何逐行验证输入文件,修复可能的错误,并将清理后的行写入另一个文件?全部内容,希望文章能够帮你解决Python:如何逐行验证输入文件,修复可能的错误,并将清理后的行写入另一个文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。