我目前使用的是python3.4.1,但我无法访问Pandas或Numpy之类的模块
我最初在excel中编写了一个VBA程序,其中原始数据在Sheet1上,新数据在Sheet2上,两个表之间的差异在Sheet3上。我的程序做了以下三件事:
由于速度非常慢,我决定尝试学习Python。在Python中,我可以比较数据,但现在我希望能够对列进行排序并对行排序。在
例如:
原创
第1列、第2列、第3列、第4列、第5列
1、b1、c11111、d1、e1
2、b2、c2、d2、e2
5,b5,c5,d5,e5,
25,b25,c25,d2555,e25
7、b7、c7、d7、e7
原始CSV 2
第1列、第2列、第3列、第4列、第5列
2、b2、c2、d2、e2
1、b1、c1、d1、e1
3、b3、c3、d3、e3
7、b7、c7、d7、e777
25、b25、c25、d25、e25
由于两个文件中第2行中的值相同,因此不会将该数据复制到两个文件的结果中。在
结果CSV 1
第1列、第2列、第3列、第4列、第5列
1、b1、c11111、d1、e1
5、b5、c5、d5、e5
7、b7、c7、d7、e7
25,b25,c25,d2555,e25
结果CSV 2
第1列、第2列、第3列、第4列、第5列
1、b1、c1、d1、e1
3、b3、c3、d3、e3
7、b7、c7、d7、e777
25、b25、c25、d25、e25
通过下面的代码,我可以完成步骤3。在
strpath = 'C://Users//User//Desktop//compare//'
strFileNameA = 'File1'
strFileNameB = 'File2'
testfile1 = open(strpath + strFileNameA + '.csv', 'r')
testfile2 = open(strpath + strFileNameB + '.csv', 'r')
testresult1 = open(strpath + strFileNameA + '-Results' + '.csv', 'w')
testresult2 = open(strpath + strFileNameB + '-Results' + '.csv', 'w')
testlist1 = testfile1.readlines()
testlist2 = testfile2.readlines()
k=1
z=0
for i,j in zip(testlist1,testlist2):
if k==1:
testresult1.write(i.rstrip('\n') + ('n'))
if i!=j:
testresult1.write(i.rstrip('\n') + ('n'))
testresult2.write(j.rstrip('\n') + ('n'))
z = z+1
k =int(k)
k = k+1
if z ==0:
testresult1.write('Exact match for ' + str(k) + ' rows')
testresult1.write('Exact match for ' + str(k) + ' rows')
testfile1.close()
testfile2.close()
testresult1.close()
testresult2.close()
这是向您介绍Python编程的一个很好的练习。 有许多字符串函数可以使许多数据处理任务更简单。 您可以在文档中查看更多的字符串函数https://docs.python.org/3/library/string.html。在
首先,我建议使用os.path.join操作系统()以创建路径字符串。 其次,我建议使用内置方法sorted()对文件的行进行排序。请注意,排序时必须小心,因为排序字符串与排序整数不同。在
步骤1使用内置的sorted函数按列1对每一行进行排序。 这是通过传递lambda函数作为关键参数来实现的。 因为Python使用从零开始的索引,所以引用x[0]使用第一列。 所以这个特殊的lambda函数只返回每行的第一列。在
步骤2遍历每个文件的所有行。如果它们都匹配,那么它们就会配对在一起。 否则,一行与空行匹配。在
我建议要么查看namedtuple:https://docs.python.org/3/library/collections.html#collections.namedtuple
或sqlite: https://docs.python.org/3/library/sqlite3.html#module-sqlite3
这两个版本都在3.4.1中提供。在
如果这些不合适(即它们是相对较小的模型点文件),可以使用内置的set对象来比较两组数据,并使用set操作来过滤:
一旦你完成了这个集合,你就可以把它转换成一个列表,对它进行排序,然后写出来。在
相关问题 更多 >
编程相关推荐