![](/img/trans.png)
[英]How to check if a string contains a specific character or not in python
[英]How to replace a string that contains a specific character in python?
我正在嘗試使用python瀏覽文本文件,並將所有包含子字符串“ e-”的字符串替換為“ 0.0”。
例如,在該行中:
0.46790 0.25440 3.5637e-0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
“ 3.5637e-0”將替換為0.0。 圍繞“ e-”的數字不一定每次出現都相同。
如果可能的話,我想修改以下代碼(將“-”替換為“ -99”)來執行此操作,但是我也歡迎其他建議:
with open(outputfile, "wt") as fout:
with open(datafile, "rt") as fin:
for line in fin:
fout.write(line.replace('- ', '-99 '))
我將這一行分開,將包含“ e-”的任何元素替換為“ 0.0”,然后重新加入它:
fout.write(' '.join(['0.0' if 'e-' in x else x for x in line.split(' ')]))
我的建議是以類似於以下方式使用正則表達式模塊:
import re
import sys
def process_file(src, dst=sys.stdout):
for line in src:
dst.write(re.sub("\d+\.\d+e\-\d+", "0.0", line))
def main(paths):
for path in paths:
with open(path, "rb") as fp:
process_file(fp)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
如果我創建具有以下內容的文件
0.46790 0.25440 3.5637e-0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
0.46790 0.25440 3.5637e-0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
並如下運行程序(稱為example.py
)
$ python example.py test.txt test.txt
我得到以下輸出
0.46790 0.25440 0.0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
0.46790 0.25440 0.0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
0.46790 0.25440 0.0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
0.46790 0.25440 0.0 0.0082447 0.0016506 0.00018180 -99 0.0010338 0.00067166 0.0043598
您可以調整程序以適合您的特定需求。
在最后一行之前添加以下兩行。
contents = [x.replace("e-", '0.0') for x in line.split()]
fout.write(' '.join(contents) + '\n')
它的作用是每當遇到空格時就將line
分割開,並在每段中應用replace
方法。 在這里,我們利用了以下事實:即使我們要查找的子字符串不在開頭的字符串中, replace
也可以使用。 修改線條后,我們將其縫合在一起,添加換行符並將其寫入文件。
您也可以使用正則表達式 ,盡管在這種情況下它可能會顯得過大。
import re
fout.write(re.sub(r"[\d.]+e-\d+", "0.0", line))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.