【问题标题】:How do I change the only the first word of every line in a text file?如何更改文本文件中每一行的唯一第一个单词?
【发布时间】: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,'...')

标签: python string file


【解决方案1】:

当您调用replace() 时,它会替换字符串中该字符的每个实例。相反,只需使用 [0] 隔离第一个字符,以便它只会在那里替换。例如:

this_file.write(line[0].replace(s,'2'))

编辑:我看到有人评论了与我输入相同的内容

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多