python - 用字符串替换文本文件列中的值

标签 python list if-statement

我有一个非常简单的问题。我有一个数据集(下面显示的小样本)

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]

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

最佳答案

没有必要在文件的两个循环中执行此操作。此外,您可以使用 -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")

延伸阅读:

关于python - 用字符串替换文本文件列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48653563/

相关文章:

python - 如何在 GUI 中启动另一个程序 (python tkinter)

python - excel文件中的整数变成 float ?

python:为什么 SQLObject 在 conn.autocommit(1) 中失败?

python - 列表操作的列表

java - 循环和统计。未打印正确的值

Python - 如何将字典作为值而不是引用传递给 defaultdict

python - 检索满足某些条件的字典

python:[[1,2],[3,4],[5,6],[7,8]] 转化为 [[1],[2,3],[4,5],[6,7 ],[8]] 反之亦然

c# - if else 或 switch 的当前 CultureName?

ios - 如果标题文本为空或未分配,如何隐藏 uibutton?