使用 Python 在文本文件中查找和替换 [英] Find and replace within a text file using Python

查看:34
本文介绍了使用 Python 在文本文件中查找和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约 400,000 行长的文本文件.我需要将此文本文件导入一个程序,该程序只接受以空格或制表符分隔的文本文件,但此文本文件以分号分隔.在我从 (Arcmap) 导出文本文件以更改分隔的程序中没有选项,并且在文本文件本身中进行查找和替换实际上需要 2 天时间.

I have a text file which is about 400,000 lines long. I need to import this text file into a program which only accepts text files which are delimited with spaces or tabs, but this text file is delimited with semi-colons. There is no option in the program I am exporting the text file from (Arcmap) to change the delimination and doing find and replace in the text file itself will literally take 2 days.

我已经搜索了一个脚本来执行此操作,但它们似乎都用空格替换了整个单词文件的 LINE,而不是单独替换每个分号,给我留下一个空文本文件.

I have searched for a script to do this but they all seem to replace the whole LINE of the word file with a space, instead of individually replacing each semi-colon, Leaving me with an empty text file.

这是我的文本文件示例:

Here is a sample of my text file:

"OID_";"POINTID";"GRID_CODE";"POINT_X";"POINT_Y"
;1;-56.000000;200900.250122;514999.750122
;2;-56.000000;200900.750122;514999.750122
;3;-56.000000;200901.250122;514999.750122
;4;-57.000000;200901.750122;514999.750122
;5;-57.000000;200902.250122;514999.750122
;6;-57.000000;200902.750122;514999.750122
;7;-57.000000;200903.250122;514999.750122
;8;-57.000000;200903.750122;514999.750122
;9;-57.000000;200904.250122;514999.750122
;10;-57.000000;200904.750122;514999.750122

我需要它看起来像这样:

I need it to look something like this:

1 -56.000000 200900.250122 514999.750122
2 -56.000000 200900.750122 514999.750122

推荐答案

这个怎么样:

sed -i 's/;/ /g' yourBigFile.txt

这不是 Python 解决方案.您必须在 shell 中启动它.但是,如果您使用记事本,我猜您使用的是 Windows.所以这里有一个 Python 解决方案:

This is not a Python solution. You have to start this in a shell. But if you use Notepad, I guess you are on Windows. So here a Python solution:

f1 = open('yourBigFile.txt', 'r')
f2 = open('yourBigFile.txt.tmp', 'w')
for line in f1:
    f2.write(line.replace(';', ' '))
f1.close()
f2.close()

这篇关于使用 Python 在文本文件中查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆