python 中将文本中多个连续的制表符或空格替换为一个制表符

 

001、

(base) root@PC1:/home/test2# ls
a.txt  test.py
(base) root@PC1:/home/test2# cat a.txt            ## 测试数据
e d  d   f        k
d                               d
e         k d f
j e f   j
(base) root@PC1:/home/test2# sed -n l a.txt       ## 查看间隔符
e d  d   f        k$
d\t\t\t\td$
e         k d f$
j e f\tj$
(base) root@PC1:/home/test2# cat test.py         ## 测试程序
#!/usr/bin/pyton

import re
in_file = open("a.txt", "r")
out_file = open("result.txt", "w")

for i in in_file:
    i = i.strip()
    i = re.sub(r"([\t ])+", "\t", i)
    print(i, file = out_file)
(base) root@PC1:/home/test2# python test.py      ## 执行程序
(base) root@PC1:/home/test2# ls
a.txt  result.txt  test.py
(base) root@PC1:/home/test2# cat result.txt      ## 执行结果
e       d       d       f       k
d       d
e       k       d       f
j       e       f       j
(base) root@PC1:/home/test2# sed -n l result.txt
e\td\td\tf\tk$
d\td$
e\tk\td\tf$
j\te\tf\tj$

 

posted @ 2022-08-09 17:09  小鲨鱼2018  阅读(505)  评论(0)    收藏  举报