简体   繁体   English

Python:替换每行文本文件中数组的索引元素

[英]Python: Replace index element of array in text file on each line

I have a text file that looks similar to:我有一个类似于以下内容的文本文件:

20, 32, 28, 32

27, 38, 30, 30

82, 39, 28, 18

29, 38, 10, 20

90, 28, 29, 09

If the value in the first column is > 50 then the remaining data is replaced with 0.如果第一列中的值 > 50,则其余数据将替换为 0。

So it should look like this:所以它应该是这样的:

20, 32, 28, 32

27, 38, 30, 30

82, 0, 0, 0

29, 38, 10, 20

90, 0, 0, 0

I am really stuck on how to go about this.我真的被困在如何解决这个问题上。 I have searched this site, but only find examples with one list eg a=[20,32,28,32] .我搜索了这个网站,但只找到了一个列表的例子,例如a=[20,32,28,32] but I have 5 different rows (is each row a separate list?)但我有 5 个不同的行(每一行是一个单独的列表吗?)

Any help would her very much welcomed.任何帮助她都会非常欢迎。

try this.尝试这个。 COde need to be changed if number of columns changes如果列数发生变化,则需要更改代码

fle =open("C:\Python27\projects\infile.txt")
lst=fle.readlines()
lst=[i.strip() for i in lst]

for i in lst:
        j=i.split(',')
        if int(j[0]) > 50:

                for k in range(1,len(j)):
                    j[k]=0

        print ','.join(str(l) for l in j)
fle.close()

Just use for loop and do for each row what you'd do for one row.只需使用for循环并对每一行执行您对一行执行的操作。

Here's an example:下面是一个例子:

with open("example_file", "r") as f:
    for line in f.readlines():
        # do what you'd do with one line
        new_line = [int(l) for l in line.split(',')]
        if new_line[0] > 50:
            new_line[1:] = [0]*(len(new_line)-1)
        # process the line further ... save it to another file?

What you have found for a single list can also be used as multiple lists.您在单个列表中找到的内容也可以用作多个列表。 Let's have a data.txt which contains out data like below:让我们有一个包含如下数据的data.txt

data.txt

20, 32, 28, 32

27, 38, 30, 30

82, 39, 28, 18

29, 38, 10, 20

90, 28, 29, 09

Now we are going to read the data and process those as required.现在我们将读取数据并根据需要处理这些数据。 Finally we will write the processed data in a new file called output_data.txt .最后,我们将处理后的数据写入一个名为output_data.txt的新文件中。 The program can be solved in the following way:该程序可以通过以下方式解决:

output_lines = []
with open("data.txt", "r") as input_file:
    input_lines = input_file.readlines()
    for line in input_lines:
        line = line.strip()
        if line!="":
            ar = list(map(int, line.split(",")))
            if ar[0] > 50:
                ar[1:] = [0] * (len(ar)-1)
            output_lines.append(", ".join([str(i) for i in ar]))
with open("output_data.txt", "w") as output_file:
    for line in output_lines:
        output_file.write(line+"\n")

output_data.txt contains: output_data.txt包含:

20, 32, 28, 32
27, 38, 30, 30
82, 0, 0, 0
29, 38, 10, 20
90, 0, 0, 0

There are many alternatives to solve this.有很多替代方法可以解决这个问题。 I have showed the most trivial one.我已经展示了最微不足道的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM