gpt4 book ai didi

python - 在分隔文件中改组列

转载 作者:行者123 更新时间:2023-11-28 19:53:45 28 4
gpt4 key购买 nike

我有一个文件:

$ cat test.txt 
a b c
d e f
x y z

我可以在 Python 中这样做来打乱列:

import random

with open('test.txt', 'r') as fin:
with open('test-shuffle.txt', 'w') as fout:
for line in fin:
line = line.strip().split('\t')
random.shuffle(line)
fout.write('\t'.join(line) + '\n')

[输出]:

$ cat test-shuffle.txt 
b c a
e d f
x y z

但是有没有办法在命令行上做到这一点?也许使用 cutawksed 等?

此外,如果我只想随机播放特定的列,是否也可以在命令行上执行,例如如果我只想洗牌第 2 列和第 3 列:

import random

with open('test.txt', 'r') as fin:
with open('test-shuffle.txt', 'w') as fout:
for line in fin:
line = line.strip().split('\t')
first , second, third = line
second_third = [second, third]
random.shuffle(second_third)
fout.write('\t'.join([first] + second_third) + '\n')

最佳答案

你没有提到 perl,但 perl 是 cut、awk、sed 的超集。它是编程语言中的瑞士军刀!

$ cat /tmp/test.tsv
a b c
d e f
x y z
$ perl -mList::Util -aln -F'\t' -e 'print join("\t", List::Util::shuffle @F)' < /tmp/test.tsv
b a c
d f e
y x z
$ perl -mList::Util -aln -F'\t' -e 'print join("\t", List::Util::shuffle @F)' < /tmp/test.tsv
c a b
e d f
x z y

哦,第二部分:

$ perl -mList::Util -aln -F'\t' -e 'print join("\t", $F[0], List::Util::shuffle @F[1..2])' < /tmp/test.tsv
a c b
d f e
x y z

关于python - 在分隔文件中改组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523334/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com