我还是Python的初学者,需要用.txt格式修改我的注解标签。.txt注解格式如下。
10 0.31015625 0.634375 0.0890625 0.2625
9 0.37109375 0.35703125 0.0671875 0.2015625
我需要将第一个数字(类号标签)替换为:
10-->7
9-->6
6-->5
10-->7 9-->6 6-->5
8-->5
我写了下面的代码,但还是远远落后于一个完整的代码,我有点卡壳。
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)
你不需要循环检查所有的替换词。你可以只检查第一个词是否在你的替换词典中。我假设你只想替换第一个单词。
word, tail = line.split(" ", 1)
if word in replacements:
word = replacements[word]
outfile.write(word + " " + tail)
你的代码并没有改变 line
即改变 word
不会改变行,因为它是一个不同的值。一般来说,字符串在Python中是不可变的(但不是列表),所以你不能通过引用来改变一个字符串对象。对字符串的操作将返回新的字符串对象。