【问题标题】:Replacing value in text file column with string用字符串替换文本文件列中的值
【发布时间】:2018-02-06 23:21:47
【问题描述】:

我遇到了一个非常简单的问题。我有一个数据集(如下所示的小样本)

22 85 203 174 9 0 362 40 0
21 87 186 165 5 0 379 32 0
30 107 405 306 25 0 756 99 0
6 5 19 6 2 0 160 9 0
21 47 168 148 7 0 352 29 0
28 38 161 114 10 3 375 40 0
27 218 1522 1328 114 0 1026 310 0
21 78 156 135 5 0 300 27 0

我需要介绍的第一个问题是用逗号替换每个空格,我使用以下代码完成了该操作

import fileinput

with open('Data_Sorted.txt', 'w') as f:
    for line in fileinput.input('DATA.dat'):
        line = line.split(None,8)
        f.write(','.join(line))

结果如下

22,85,203,174,9,0,362,40,0
21,87,186,165,5,0,379,32,0
30,107,405,306,25,0,756,99,0
6,5,19,6,2,0,160,9,0
21,47,168,148,7,0,352,29,0
28,38,161,114,10,3,375,40,0
27,218,1522,1328,114,0,1026,310,0
21,78,156,135,5,0,300,27,0

我的下一步是从最后一列中获取值,检查它们是否小于 2 并将其替换为字符串 'nfp'。

我可以用以下内容分隔最后一列

for line in open("Data_Sorted.txt"):
    columns = line.split(',')

    print columns[8]

我的问题是实现用字符串替换值的条件,然后我不确定如何将修改后的列放回原始数据集中。

【问题讨论】:

    标签: python list if-statement


    【解决方案1】:

    无需在文件的两个循环中执行此操作。此外,您可以使用-1 来索引该行中的最后一个元素。

    import fileinput
    
    with open('Data_Sorted.txt', 'w') as f:
        for line in fileinput.input('DATA.dat'):
            # strip newline character and split on whitespace
            line = line.strip().split()
    
            # check condition for last element (assuming you're using ints)
            if int(line[-1]) < 2:
                line[-1] = 'nfp'
    
            # write out the line, but you have to add the newline back in
            f.write(','.join(line) + "\n")
    

    进一步阅读

    【讨论】:

      【解决方案2】:

      您需要将 columns[8] 转换为 int 并比较是否小于 2。

      for line in open("Data_Sorted.txt"):
          columns = line.split(',')
          if (int(columns[8]) < 2):
              columns[8] = "nfp"
          print columns
      

      【讨论】:

        猜你喜欢
        • 2019-05-16
        • 2016-04-01
        • 1970-01-01
        • 2022-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-18
        相关资源
        最近更新 更多