【问题标题】:Replace word in text file comma separated with word in a specific column with Python用Python替换文本文件逗号分隔的单词与特定列中的单词
【发布时间】:2014-07-29 03:25:50
【问题描述】:

抱歉,我只是在说明 Python,需要一些灯

我有一个如下列表:

$ cat server.txt
column1, column2, column3, column4, column5
server1, windows, 120, running , 1
server2, linux, 250, offline , 1
server3, centos, 60, maintenance, 0
server4, windows, 123, running, 1
server5, linux, 145, offline, 0

我需要将第二列替换为其他值,例如:

第 5 列中的所有 1 都被替换为 noissue 和 0 替换为 issue 但只有在第 5 列,因为我不想让第 3 列受到更改的影响

非常感谢

【问题讨论】:

  • 阅读每一行。用逗号分隔每一行。更改最后一个元素(您要修改的那个)。每行写入一个新文件。重命名文件。

标签: python text replace


【解决方案1】:

您应该为此使用csv 模块:

import csv

with open('server.txt', 'r') as infile, open('server_modified.txt','w') as outfile:
   reader = csv.reader(infile, delimiter=',')  # ',' is the default, but this shows
                                               # you how to change it in the future
   writer = csv.writer(outfile, delimiter=',')
   writer.writerow(next(reader)) # This will write the first row (your header)
                                 # directly to the output file

   for row in reader:
      if row[-1] == '1':
         row[-1] = 'noissue'

      if row[-1] == '0':
         row[-1] = 'issue'

      writer.writerow(row)

【讨论】:

    【解决方案2】:

    你可以这样做

    mapping = {'0':'issue', '1':'noissue'}
    for line in sys.stdin:
      fields = line.split(',')
      if fields[4].strip() in mapping:
        fields[4] = mapping[fields[4].strip()]
      print ','.join(fields)
    

    这将适用于标准输入并写入stdout,因此您必须像这样调用您的程序

    $ python program.py < server.txt > output.txt
    

    如果列中既没有“0”也没有“1”,则该值不会改变。如果您也想更改其他值,可以调整mapping

    请注意,该程序不单独处理第一行(请参阅 julinenc 的帖子以了解如何完成)。由于您的第一行中没有“0”或“1”,因此它将适用于您发布的示例。

    还要注意strip() 方法的使用,这可以消除“0”和“1”周围可能存在的额外空格

    【讨论】:

    • 很好,但是你可以用fields[4] = mapping.get(fields[4].strip(), fields[4]) 替换你的if 循环,get() 有一个可选的第二个参数,它是如果键不存在时返回的值。它默认为None,但在这里我将其替换为fields[4] 的值。实际上,“如果存在替换,则获取它,否则返回查找的值”。
    • 感谢 MartinStettner 提供代码。这是有效的,但输出在行之间添加了空白行。有没有办法避免这种情况?
    • 感谢 Burhan Khalid,我可能有一些只有 2 列的行,如果值不存在,您提供的代码会出错
    【解决方案3】:

    如果您确定要替换的列仅包含 0 和 1,这将起作用。

    firstline = True
    with open("server.txt") as f:
        with open("output.txt", "w") as fw:
            for line in f.readlines(): # For each line in server.txt
    
                if firstline: # Do not process the header line
                    firstline = False
                    continue
    
                if line[-2] == "1": # -2 because -1 is the line return character
                    line = line[:-2] + "noissue\n"
                else:
                    line = line[:-2] + "issue\n"
                fw.write(line)
    

    【讨论】:

    • 感谢 julienc,您的代码按预期工作,但我还有另一个问题 :),如果它们在 column2 中并且知道服务器名称可能长度不同?
    • 好吧,在这种情况下,你应该看看另外两个答案。我的需要太多改变才能适应这些新条件......
    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多