简体   繁体   English

替换文本文件(注释文件)中每一行的第一个单词(标签)-Python代码

[英]Replacing first word (label) of every line in a text file (annotation files)-Python Code

I am still beginner with the Python and need to modify labels of my annotations with.txt format.我仍然是 Python 的初学者,需要用 .txt 格式修改我的注释标签。 The.txt annotation format looks like below: .txt 注释格式如下所示:

10 0.31015625 0.634375 0.0890625 0.2625
9 0.37109375 0.35703125 0.0671875 0.2015625

And I need to replace the first number (class number/label) as:我需要将第一个数字(类号/标签)替换为:

  • 10-->7 10-->7

  • 9-->6 9-->6

  • 6-->5 6-->5

  • 11-->8 11-->8

  • 8-->5 8-->5

    I have written the following code but still it is far behind a complete one and I am kinda stuck.我已经编写了以下代码,但仍然远远落后于完整的代码,我有点卡住了。

    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)

You don't have to loop through all of the replacements.您不必遍历所有替换。 You can just check if the first word is in your replacements dictionary.您可以检查第一个单词是否在您的替换字典中。 I'm assuming you only want to replace the first word.我假设您只想替换第一个单词。

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

outfile.write(word + " " + tail)

Your code doesn't change line , ie changing word does not change line as it is a different value.您的代码不会更改line ,即更改word不会更改 line 因为它是不同的值。 In general, strings are immutable in Python (but not lists), so you can't change a string object through a reference.通常,字符串在 Python(但不是列表)中是不可变的,因此您不能通过引用更改字符串 object。 Operations on strings will return new string objects.对字符串的操作将返回新的字符串对象。

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

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