0

我很抱歉,但我是 Python 新手,我有文件包含这样的数据

x1 y1 z1 w1 x2 y2 z2 w2 .. xn yn zn wn

我想在每个 w 之后附加一些数字。所以基本上在txt文件中的每4个元素之后。

请问有什么建议吗?非常感谢

更新:txt文件中的数据都是字符串。我能够转换它们

f = open("test.txt","r+").readlines()
for line in f:
    tmp = line.strip().split(",")
    values = [float(v) for v in tmp]
    my_data = [1 1 2 23 1]
    a = np.insert(a,slice(0,None,4),my_data)  
    np.savetxt(filename, a)

附加部分仍然不起作用。

4

3 回答 3

1

您必须首先将此文件读入数组,插入项目并将其保存回来(假设您的文本文件的名称是filename):

import numpy as np
your_number = #number you want to insert OR a list of numbers you want to insert consecutively in those locations
a = numpy.loadtxt(filename)
a = np.insert(a,slice(0,None,4),your_number)
np.savetxt(filename, a)

例子:

a = np.zeros(10)
#[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
l = [1,2,3]
a = np.insert(a,slice(0,None,4),l)

输出

[1. 0. 0. 0. 0. 2. 0. 0. 0. 0. 3. 0. 0.]
于 2020-07-09T18:47:18.520 回答
0

如果您不完全确定 w 元素是否像您说的那样存在,那么快速而肮脏。“数据”是您正在读取的文件。我假设您的数据是在每一行都像您所说的格式那样被读取的。我们在默认空白处分割线并获取线的数组表示。然后我们遍历每个数组,并在找到匹配项的地方用新词替换旧词。

注意:字符串是不可变的,因此最好使用 enumerate 之类的方式将数组中的单词实际替换为新单词。

  with open("data", "r") as f:
       tot_lines = [line.split() for line in f]
       for line in tot_lines:
           for key, word in enumerate(line):
               if word[0] == "w":
                   line[key] = word + str(9999)
       print(tot_lines)
于 2020-07-09T18:29:08.187 回答
0

你的问题就是你的问题。首先,你说:

我有文件有这样的数据

x1 y1 z1 w1 x2 y2 z2 w2 .. xn yn zn wn

但是在你的代码中你这样做: split(",") 所以你的数据真的看起来像:

x1,y1,z1,w1,x2,y2,z2,w2,...,xn,yn,zn,wn

你希望你的数据看起来像:

x1,y1,z1,w1,v1,x2,y2,z2,w2,v2,...,xn,yn,zn,wn,vn

vn值来自哪里:

my_data = [1 1 2 23 1]

我们注意到这不是有效的 Python 语法,因此您发布的代码实际上并没有运行。对于多行输入,少量数据似乎也很奇怪,但让我们继续吧。我们正在查看五组四个数据项或每行 20 个数字作为输入。例如,如果我们有一个五行文件,我们会看到如下内容:

> cat test.txt
47,18,96,31,48,33,64,21,92,35,78,62,56,23,25,47,35,9,15,9
34,38,64,72,66,69,18,57,92,3,58,17,96,19,53,63,97,86,24,41
2,52,22,59,27,58,82,45,90,24,26,51,47,43,17,14,8,54,4,58
13,99,78,61,99,8,65,10,62,56,91,66,45,18,41,50,75,95,62,80
48,30,18,46,93,82,25,15,93,1,45,88,22,97,54,47,54,64,16,91
>

附加部分仍然不起作用。

这很好,因为附加真的不是去这里的正确方法。要插入我们的新数据,使用基本的 Python sans numpy,我会做类似的事情:

my_data = [1, 1, 2, 23, 1]

with open("test.txt") as input_file:
    with open("revised.txt", 'w') as output_file:

        for line in input_file:
            array = line.rstrip().split(',')

            for index, datum in enumerate(my_data, 1):
                array.insert(index * 5 - 1, str(datum))

            print(','.join(array), file=output_file)

(索引数学index * 5 - 1很棘手,因为我们添加每个新项目时数组索引会发生变化。)结果输出:

> cat revised.txt 
47,18,96,31,1,48,33,64,21,1,92,35,78,62,2,56,23,25,47,23,35,9,15,9,1
34,38,64,72,1,66,69,18,57,1,92,3,58,17,2,96,19,53,63,23,97,86,24,41,1
2,52,22,59,1,27,58,82,45,1,90,24,26,51,2,47,43,17,14,23,8,54,4,58,1
13,99,78,61,1,99,8,65,10,1,62,56,91,66,2,45,18,41,50,23,75,95,62,80,1
48,30,18,46,1,93,82,25,15,1,93,1,45,88,2,22,97,54,47,23,54,64,16,91,1
>

如果这不是您想要做的,请重写您的问题,澄清您的文件格式,明确说明您的目标并提供好的示例。

于 2020-07-12T01:35:34.920 回答