【发布时间】:2021-09-05 02:31:26
【问题描述】:
所以我实际上已经弄清楚了如何更改第一个单词,但问题不只是仅更改第一个单词。 所以我有一个文件,例如:
2 0.268278 0.356394 0.027123 0.044025
4 0.241745 0.528302 0.035377 0.035639
4 0.257075 0.491614 0.037736 0.033543
5 0.275354 0.307128 0.060142 0.062893
0 0.283019 0.551363 0.115566 0.572327
0 0.043042 0.292453 0.076651 0.159329
我想把它改成:
3 0.268278 0.356394 0.027123 0.044025
5 0.241745 0.528302 0.035377 0.035639
5 0.257075 0.491614 0.037736 0.033543
9 0.275354 0.307128 0.060142 0.062893
0 0.283019 0.551363 0.115566 0.572327
0 0.043042 0.292453 0.076651 0.159329
所以我的代码是:
source = 'C:/Users/asmita.nandi/Downloads/Kitchen_black&white/Annotations1'
for root, dirs, filenames in os.walk(source):
for f in filenames:
this_file = open(os.path.join(source, f), "r")
this_files_data = this_file.readlines()
this_file.close()
# opens all txt file in directory
this_file = open(os.path.join(source, f), "w")
for line in this_files_data:
s=line[0]
if line[0] in "1" :
this_file.write(line.replace(s,'2'))
if line[0] in "2" :
this_file.write(line.replace(s,'3'))
if line[0] in "0":
this_file.write(line)
if line[0] in "3":
this_file.write(line.replace(s,'4'))
if line[0] in "4":
this_file.write(line.replace(s,'5'))
if line[0] in "5":
this_file.write(line.replace(s,'9'))
this_file.close()
所以我的代码所做的不仅是更改第一个单词,而且还更改了该行中数字的任何其他实例。所以会发生这样的事情:
3 0.359080 0.359539 0.037133 0.060797
9 0.369104 0.289119 0.070799 0.079472
9 0.678696 0.143606 0.099429 0.090147
5 0.307193 0.590157 0.038915 0.052511
0 0.392099 0.620545 0.173349 0.746331
0 0.653892 0.479036 0.135613 0.752621
我做错了什么?
【问题讨论】:
-
您正在替换整行。尝试这样做:line[0].replace(s,'...')