python - 提取文本文件的特定部分
问题描述
我有一个文本文件如下:
A B C D E
1 1 2 1 1e8
2 1 2 3 1e5
3 2 3 2 2000
50 2 3 2 2000
80 2 3 2 2000
...
1 2 5 6 1000
4 2 4 3 1e4
50 3 6 4 5000
120 3 5 2 2000
...
2 3 2 3 5000
3 3 4 5 1e9
4 3 2 3 1e6
7 3 2 3 43
...
我需要一个代码来遍历这个文本文件并在第一列[A]中提取具有相同编号的行并保存在不同的文件中,
例如对于第一列 = 1 和 ...
1 1 2 1 1e8
1 2 5 6 1000
我用while循环编写了代码,但问题是这个文件非常大,而使用while循环它可以为文本中不存在的数字工作,并且需要很长时间才能完成,
谢谢你的帮助
解决方案
警告
下面的两个示例都将覆盖input_<number>.txt
在它们运行的路径中调用的文件。
使用awk
rm input_[0-9]*.txt; awk '/^[0-9]+[ \t]+/{ print >> "input_"$1".txt" }' input.txt
前面部分/^[0-9]+[ \t]+/
进行正则表达式匹配以仅选择以整数开头的行,第二部分将{ print >> "input_"$1".txt" }
这些行打印到名为 的文件input_<number>.txt
中,在文件的第一列中找到每个数字对应的行。
使用 Python
import sys
import os
fn = sys.argv[1]
name, ext = os.path.splitext(fn)
with open(fn, 'r') as f:
d = {}
for line in f:
ind = line.split()[0]
try:
ind = int(int)
except ValueError:
continue
try:
d[ind].write(line)
except KeyError:
d[ind] = open(name + "_{}".format(ind) + ext, "w")
d[ind].write(line)
for dd in d.values():
dd.close()
使用 Python(避免打开文件句柄过多)
在这种情况下,您必须在手动运行代码之前删除任何旧的输出文件,使用rm input_[0-9]*.txt
import sys
import os
fn = sys.argv[1]
name, ext = os.path.splitext(fn)
with open(fn, 'r') as f:
for line in f:
ind = line.split()[0]
try:
ind = int(int)
except ValueError:
continue
with open(name + "_{}".format(ind) + ext, "a") as d:
d.write(line)
提高打开文件句柄数的限制
如果您是计算机上的 sudoer,则可以ulimit -n <number>
根据此答案使用 增加进程打开文件句柄的限制。
推荐阅读
- android - Firebase 动态链接 - 从 Play 商店安装应用程序后无法在 android 中获取 Url
- c# - 日期从和到过滤
- reactjs - 反应读取子状态
- go - 在 Go 中运行 Python 命令
- typescript - 统一模型和模式
- javascript - 浏览器如何修复损坏的 HTML?
- php - 将数据库中的数据显示为选择中的选项
- apache-spark - Py4JJavaError:org.apache.spark.SparkException:在 awaitResult 中抛出异常
- php - 如何在 laravel 5.6 中下载 pdf 文件?
- javascript - 更改变量名后我的代码停止运行