【发布时间】:2014-06-23 21:17:27
【问题描述】:
我有两个文本文件:
file1.txt:
a,1
b,3
c,5
d,-4
和file2.txt:
sample1
a,12
b,10
c,4
d,6
sample2
a,5
b,8
c,6
d,12
sample3
a,3
b,6
c,9
d,10
我想要做的是从 file2.txt 中所有示例中的相应字母中减去 file1.txt 中给定字母的值,并创建多个文件,因此输出如下所示:
sample1 的第一个文件,sample1.txt
sample1.txt
a,11 # 12-1 as 1 from file1.txt was subtracted from 12 in file2.txt
b,7 # 10-3
c,-1 # 4-5
d,10 # 6-(-4)
然后为sample2分离文件,sample2.txt:
sample2.txt
a,4 # 5-1 as 1 from file1.txt was subtracted from 5 in file2.txt
b,5 # 8-3
c,1 # 6-5
d,16 # 12-(-4)
对于 sample3 也是如此。
我尝试循环遍历 file2.txt,但由于我的原始 file2.txt 有超过 1000 个样本,这需要很长时间,有没有更快的 Pythonic 方式来做到这一点?
干杯, 凯特
【问题讨论】:
-
遍历每个文件并构建一个
dict()(每个文件),然后您就可以轻松提取相关的字母值。
标签: python text data-manipulation