【问题标题】:Find line number of replaced key value查找替换键值的行号
【发布时间】:2023-02-05 01:19:08
【问题描述】:

如何获取替换键值的行号? 目前它的功能不同,我如何在替换字符串时将它组合成行号。

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")

【问题讨论】:

  • 什么是filedata?请使用 filedata 的定义编辑您的代码,以便代码 sn-p 变为 minimal reproducible example
  • 这段代码中有很多非常基本的错误,以至于无法运行它,并且很难单独根据代码确定意图是什么。如果你完全被卡住了并且需要帮助让代码工作,你应该写一份关于代码内容的英文描述应该这样做可以建议代码更改,使您更接近您的意图。
  • 抱歉,我已经更新了问题。谢谢@Samwise

标签: python python-3.x dictionary for-loop replace


【解决方案1】:

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

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("
"),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 4

print(filedata)

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

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 2014-01-26
    • 2012-02-12
    • 2017-04-07
    • 2011-05-14
    • 2020-06-24
    • 2013-07-22
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多