在Python中对两个文本文件进行类似SQL的JOIN,有内置方法吗?

3 投票
2 回答
1839 浏览
提问于 2025-04-16 03:37

我常常需要做的一个任务是对两个文本文件进行类似SQL的连接操作。也就是说,我想从“左边”的文件和“右边”的文件中创建一个新文件,使用它们之间共享的某个标识符列来进行连接。有时候还需要一些变种,比如外连接等。

当然,我可以写一个简单的脚本来以通用的方式完成这个任务,但有没有什么Python模块——内置的或者可以安装的——能够做到这一点?如果能处理超大的文件,那就更好了。

编辑:

  • 我知道有PyTables,但这对于平面文本文件来说是最简单的解决方案吗?
  • 我所说的“超大文件”是指有时候“左边”的文件大到无法在内存中存储。
  • 到目前为止,缺乏Python的解决方案让我有点担心。我是不是在用错工具或方法?我之所以想要一个Python库,是为了方便在每一行上添加其他转换(比如验证标识符等)。

2 个回答

0

如果你在使用类Unix系统或者Cygwin,可以看看join命令——它可能正好能满足你的需求。

[26] % join --help
Usage: join [OPTION]... FILE1 FILE2
For each pair of input lines with identical join fields, write a line to
standard output.  The default join field is the first, delimited
by whitespace.  When FILE1 or FILE2 (not both) is -, read standard input.

  -a FILENUM        print unpairable lines coming from file FILENUM, where
                      FILENUM is 1 or 2, corresponding to FILE1 or FILE2
  -e EMPTY          replace missing input fields with EMPTY
  -i, --ignore-case ignore differences in case when comparing fields
  -j FIELD          equivalent to `-1 FIELD -2 FIELD'
  -o FORMAT         obey FORMAT while constructing output line
  -t CHAR           use CHAR as input and output field separator
  -v FILENUM        like -a FILENUM, but suppress joined output lines
  -1 FIELD          join on this FIELD of file 1
  -2 FIELD          join on this FIELD of file 2
      --help     display this help and exit
      --version  output version information and exit

Unless -t CHAR is given, leading blanks separate fields and are ignored,
else fields are separated by CHAR.  Any FIELD is a field number counted
from 1.  FORMAT is one or more comma or blank separated specifications,
each being `FILENUM.FIELD' or `0'.  Default FORMAT outputs the join field,
the remaining fields from FILE1, the remaining fields from FILE2, all
separated by CHAR.

Important: FILE1 and FILE2 must be sorted on the join fields.

Report bugs to <bug-coreutils@gnu.org>.

如果你想要更复杂的操作,或者你一定要用Python来做,可以考虑把文件读入一个内存中的SQLite数据库——这样你就可以使用SQL的全部功能来合并和处理数据。

补充说明刚刚看到文件太大,无法全部放进内存。你仍然可以使用SQLite,但可以创建一个临时的磁盘数据库。

1

[疯狂的想法]

这些文件能放进你电脑的内存里吗?如果可以的话,你可以用SQLite把它们加载到表格里,然后用SQL随意连接它们。

[/疯狂的想法]

更新

算了。提问者说其中一个文件太大,无法存放在内存里。。可以看看这个回答,作者是@Dave Kirby。SQLite可以和磁盘上的数据库一起使用。

撰写回答