python - 如何用 shell 脚本中另一个文件的值替换文件中字段(列)的特定值?

标签 python shell

我有两个文件,分别是 A.txt 和 B.txt。 A.txt 有如下所示的三列

0 0 17
0 1 17
0 2 4
0 3 50
0 4 90 
....
.... 

我必须用保存在 B.txt 中的相应 map 值替换第三列值,如下所示

1 1
2 1
3 1
4 1
..
17 5
..
50 8
..
90 11
..

B.txt中第一列的值和A.txt中第三列的值相同,我需要创建一个新文件(比如C.txt),其前两列与A.txt相同A.txt 但第三列包含相应的 map 值。 C.txt的样本如下所示

0 0 5, 0 1 5, 0 2 1, 0 3 8, 0 4 11, ..., ...

注意

我有 400000 个文件来执行此操作,因此速度很重要。我为此编写了一个程序,但运行速度很慢。如果不是创建新文件 (C.txt) 替换可以节省时间,那么该解决方案也是可以接受的。

while read line
do

     origPhoneme=`echo $line| cut -d " " -f3` 
     while read mapLine
     do
        mapPhone=`echo $mapLine | cut -d " " -f1`
        replacementPhone=`echo $mapLine | cut -d " " -f2`
        if [ $mapPhone == $origPhoneme ]
        then
             echo $replacementPhone >> checkFile
             break
        fi
     done < B.txt
done< A.txt

paste -d ""A.txt checkFile > C.txt

通过使用此代码,C.txt 文件包含我不想要的 A.txt 的第三列

最佳答案

Python(或 shell 脚本)应该足够快 - 您的任务主要受 I/O 速度限制,而不是处理速度。

所以我建议使用这样的 Python 方法:

B.txt读入字典中进行快速查找:

with open("B.txt") as file:
    B = dict(line.strip().split() for line in file)

然后处理A.txt,创建C.txt:

with open("A.txt") as infile, open("C.txt", "w") as outfile:
    for line in infile:
        start, end = line.strip().rsplit(None, 1)
        outfile.write("{0} {1}\n".format(start, B[end]))

关于python - 如何用 shell 脚本中另一个文件的值替换文件中字段(列)的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407323/

相关文章:

python - flake8:仅忽略整个文件中的 F401 规则

bash - Bash:从docker-compose.yml获取容器名称列表

json - bash:遍历由索引选择的 JSON 数组的成员

bash - 使用 awk 的最近邻居

java - 使用 Java 运行 shell 脚本将文件复制到 docker 返回错误

linux - 如何从终端定期运行命令(每 5 秒)

python - python中的Numba jit警告解释

python - Django python 中的 mysql 'LIKE'

python - Django 设置.py 错误

python - Pandas 替换为字符串和整数 - 不正确的行为?