【发布时间】:2018-11-02 00:11:33
【问题描述】:
我正在处理两个包含数百万条记录的文件。只是分享测试数据来解释我面临的问题。例如,tx_match.txt 包含所有记录。并且 txid_time.txt 只有少数具有时间戳的记录。我想要的输出如下所示,想法是合并来自主数据库的附加列信息。请注意,我不允许使用 pandas 库。
tx_match.txt
col1 col2 col3 col4
171 9 9 5000000000
183 171 9 4000000000
185 183 9 3000000000
187 185 9 2900000000
192 187 187 100000000
227 185 185 100000000
255 187 9 2800000000
504 367 367 5000000000
504 192 192 100000000
504 255 255 1000000000
533 293 293 5000000000
555 533 533 2500000000
txid_time.txt
col1 col2
227 2017-02-10
255 2017-01-10
504 2017-02-09
我想要的输出是:
227 185 185 100000000 2017-02-10
255 187 9 2800000000 2017-01-10
504 367 367 5000000000 2017-02-09
504 192 192 100000000 2017-02-09
504 255 255 1000000000 2017-02-09
到目前为止,我已经这样做了:
import csv
d={}
fin = open("txid_match.txt","r")
for line in fin:
try:
line = line.rstrip()
f = line.split("\t")
k=f[0]
v=f[1]
d[k]=v
except IndexError:
continue
fin.close()
#print(d)
fin = open("txid_time.txt","r")
fout = open("txmatch_time.txt",'w')
foutWriter=csv.writer(fout)
for line in fin:
try:
line = line.rstrip()
f = line.split("\t")
txid=f[0]
prvtxid=d[txid]
foutWriter.writerow([f[0]+"\t"+f[1]+"\t"+prvtxid])
except IndexError:
continue
except KeyError:
continue
fin.close()
fout.close()
提前感谢您的支持。
【问题讨论】:
-
你不允许使用任何库吗?还是不是熊猫库?
-
@Abhishek ,像 csv 这样的基本 python 库,我可以使用。你有没有任何图书馆的解决方案?期待看到,谢谢。
-
您可以编辑 .txt 文件吗?例如我会删除所有空格,并用 ; 分隔列并添加标题。这将使阅读 .txt 文件更容易。
-
@J.A.Cado,抱歉弄乱了间距,因为最初,我删除了一些列。现在,我刚刚添加了标题并在列之间添加了 4 个间距。谢谢
标签: python python-2.7 dictionary merge inner-join