我仍然是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
- 11-> 8
- 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)
您不必遍历所有替换项。您只需检查第一个单词是否在替换字典中。我假设您只想替换第一个单词。