首页 > 解决方案 > 替换文本文件(注释文件)中每一行的第一个单词(标签)-Python代码

问题描述

我仍然是 Python 的初学者,需要用 .txt 格式修改我的注释标签。.txt 注释格式如下所示:

10 0.31015625 0.634375 0.0890625 0.2625
9 0.37109375 0.35703125 0.0671875 0.2015625

我需要将第一个数字(类号/标签)替换为:

    replacements = {'6':'5', '9':'6', '10':'7', '11':'8', '8':'5'}
    
    with open('data.txt') as infile, open('out.txt', 'w') as outfile:
        for line in infile:
            word=line.split(" ",1)[0]
            for src, target in replacements.items():
                word = word.replace(src, target)
            outfile.write(line)

标签: pythonannotationslabel

解决方案


您不必遍历所有替换。您可以检查第一个单词是否在您的替换字典中。我假设您只想替换第一个单词。

word, tail = line.split(" ", 1)
if word in replacements:
  word = replacements[word]

outfile.write(word + " " + tail)

您的代码不会更改line,即更改word不会更改行,因为它是不同的值。通常,字符串在 Python 中是不可变的(但不是列表),因此您无法通过引用更改字符串对象。对字符串的操作将返回新的字符串对象。


推荐阅读