我有两种格式的文件
的1.txt
1233445555,
4333333322,
12223344343
22333444337
33443445555
2.txt
42202123456,
42202234567,
42203234568,
42204356789,
我想要的是通过比较文件1的第一列来获取文件2中第一列的位置,如果在文件1中找到文件2的第1列中的第一个字符串,则输出应该给出该位置file1中的行
从我的awk命令我能够按照2.csv的第1列对文件进行排序,但无法找到每行的位置
awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' 1.csv 2.csv > 3.txt
cat 3.csv
38202123456
48202234567
672032345682
76204356789
88205443456
答案 0 :(得分:1)
首先创建一个字典键=>第二个文件的行索引,使用字典理解,索引从1开始。
然后打开文件1并在文件2中查找密钥。如果找到写入数据&位置,使用writerows
和生成器理解作为参数,因此性能最大化。
import csv
# create row => index dictionary
with open("file2.csv") as f2:
# we only need first row
# so we discard the rest using *_ special syntax when unpacking rows
d = {first_cell:i+1 for i,(first_cell,*_) in enumerate(csv.reader(f2))}
# write output
with open("file1.csv") as f1, open("3.csv","w",newline='') as f3:
csv.writer(f3).writerows([k,"{} -position {}".format(v,d[k])] for k,v in csv.reader(f1) if k in d)
注意:python 2用户应该替换:
{first_cell:i+1 for i,(first_cell,*_) in enumerate(csv.reader(f2))}
{row[0]:i+1 for i,row in enumerate(csv.reader(f2))}
open("3.csv","w",newline='')
open("3.csv","wb")
答案 1 :(得分:0)
请在下面找到基于Python index method的初始问题的解决方案。
# Reading the CSV files
with open( '1.csv' ) as f1:
rows_1 = f1.read().split('\n')
with open( '2.csv' ) as f2:
rows_2 = f2.read().split('\n')
# Extracting the colmuns of each file
for i in xrange( len( rows_1) ):
rows_1[i] = rows_1[i].split(',')
# ...note that from the second CSV file we need only the first column
for i in xrange( len( rows_2) ):
rows_2[i] = rows_2[i].split(',')[0]
# Comparing the data
res = []
for r in rows_1:
try:
res.append( r[0] + ',' + r[1] +
' -position ' + str( rows_2.index( r[0] )+1 ) )
except:
pass
# Saving the result in a new file
with open('3.csv', 'w') as f3:
for r in res:
f3.write( r+'\n' )