简体   繁体   English

查找并替换整行python

[英]find and replace whole line python

I have a file like this.. 我有一个这样的文件..

xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
a b c invalid #seperated by tab
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx

I need to replace abc invalid to ab reviewed rd # separated by tab Basically any line that ends with invalid, I need to replace that line with reviewed rd // separated by tab but I have to keep the first and second words on that line (only replace 3rd and 4th). 我需要将abc invalid替换为ab reviewed rd # separated by tab基本上任何以无效结尾的行,我都需要用reviewed rd // separated by tab替换该行, reviewed rd // separated by tab但是我必须保留该行的第一个和第二个单词仅替换第3和第4个)。

I have started doing something like this, but this won't exactly do what I want. 我已经开始做这样的事情,但这并不能完全满足我的要求。

f1 = open('fileInput', 'r')
f2 = open('fileInput'+".tmp", 'w')
for line in f1:
    f2.write(line.replace('invalid', ' reviewed'+\t+'rd'))
f1.close()
f2.close()

regex can be an option but I'm not that good with it yet. regex可以是一个选择,但是我还不太满意。 Can someone help. 有人可以帮忙吗?

PS a,b and c's are variables.. I can't do an exact search on 'a','b','c'. PS a,b和c是变量。.我无法对'a','b','c'进行精确搜索。

f1 = open('fileInput', 'r')
f2 = open('fileInput+".tmp"', 'w')
for line in f1:
    if line[:-1].endswith("invalid"):
        f2.write("\t".join(line.split("\t")[:2] + ["reviewed", "rd"]) + "\n")
    else:
        f2.write(line)
f1.close()
f2.close()
import re

pattern = re.compile(r'\t\S+\tinvalid$')
with open('data') as fin:
    with open('output', 'w') as fout:
        for line in fin:
            fout.write(pattern.sub('\treviewd\trd', line))
with open('input.tab') as fin, open('output.tab', 'wb') as fout:
    tabin = csv.reader(fin, delimiter='\t')
    tabout = csv.writer(fout, delimiter='\t')
    for row in tabin:
        if len(tabin) != 4:
            continue # or raise - whatever
        if row[-1] == 'invalid':
            tabout.writerow(row[:2] + ['reviewed', 'rd'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM