【问题标题】:Taking the specific column for each line in a txt file python为txt文件python中的每一行获取特定列
【发布时间】:2019-08-01 00:27:57
【问题描述】:

我有两个 txt 文件。 第一个是每行包含一个数字,如下所示:

22
15
32
53
.
.

另一个文件每行包含 20 个连续数字,如下所示:

0.1 2.3 4.5 .... 5.4
3.2 77.4 2.1 .... 8.1
....
.
.

根据第一个 txt 中的给定数字,我想分隔其他文件。例如,在第一行的第一个 txt 中我有 22,这意味着我将使用 20 列的第一行和两列的第二行以及我将删除的第二行的其他列。然后我将查看第一个 txt 的第二行(它是 15),这意味着我将从其他文件的第三行中取出 15 列,并且将删除第三行的其他列,依此类推。我该怎么做?

with open ('numbers.txt', 'r') as f:
with open ('contiuousNumbers.txt', 'r') as f2:
with open ('results.txt', 'w') as fOut:
   for line in f:
   ...

谢谢。

【问题讨论】:

  • 您能提供一个示例输出吗?
  • 它看起来像 continueNumbers.txt 但行数更少(最后行号与 numbers.txt 相同)。假设我们在 continueNumbers.txt((第一行)0.1 0.2 0.3 (第二行)2 0.2 0.3 (第三行) 0.7 0.5 3 (第四行) 0.2 3 4 (第五行) 1 2 3 (第六行)2 3 4 以此类推)。 Numbers.txt 是这样的((第一行)1(第二行)7(第三行)4,依此类推)。输出将是这样的((第一行)0.1(第二行)2 0.2 0.3 0.7 0.5 3 0.2(第三行)1 2 3 2 等等)。我希望我能说出来。

标签: python bash shell


【解决方案1】:

对于您遍历第一个文件的每一行上的数字,将该数字设为要读取的目标总数,以便您可以使用while 循环继续在第二个文件对象上使用next 来读取数字并从总数中减少数字的数量,直到总数达到 0。使用总数中较低的数字和数字的数量对数字进行切片,以便仅输出请求的数字数量:

for line in f:
    output = []
    total = int(line)
    while total > 0:
        try:
            items = next(f2).split()
            output.extend(items[:min(total, len(items))])
            total -= len(items)
        except StopIteration:
            break
    fOut.write(' '.join(output) + '\n')

所以给定第一个文件:

3
6
1
5

和第二个文件:

2 5
3 7
2 1
3 6
7 3
2 2
9 1
3 4
8 7
1 2
3 8

输出文件将具有:

2 5 3
2 1 3 6 7 3
2
9 1 3 4 8

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多