python-3.x 查找替换键值的行号

xyhw6mcr  于 2023-02-06  发布在  Python
关注(0)|答案(1)|浏览(113)

如何获得被替换键值的行号?目前对于它的函数不同,如何合并它,使其在替换字符串时具有行号。

filedata= is a path of file. In which i need to replace strings.

old_new_dict = {'hi':'bye','old':'new'}

def replace_oc(file):
    lines = file.readlines()

    line_number = None
    for i, line in enumerate(lines):
        line_number = i + 1
        break
    return line_number

def replacee(path, pattern):
    for key, value in old_new_dict.items():
        if key in filedata:
            print("there")
            filedata = filedata.replace(key, value)
        else:
            print("not there")
zzzyeukh

zzzyeukh1#

你可以把文件数据分解成行,在实际替换之前检查要替换的单词。例如:

filedata = """The quick brown fox
jumped over
the lazy dogs
and the cow ran away 
from the fox"""

old_new_dict = {"dogs":"cats", "crazy":"sleeping","fox":"cow"}

for key,value in old_new_dict.items():
    lines = [i for i,line in enumerate(filedata.split("\n"),1) if key in line]
    if lines:
        filedata = filedata.replace(key,value)
        print(key,"found at lines",*lines)
        
    else:
        print(key,"is not there")

输出:

# dogs found at lines 3
# crazy is not there
# fox found at lines 1 5

print(filedata)

The quick brown cow
jumped over
the lazy cats
and the cow ran away 
from the cow

相关问题