![](/img/trans.png)
[英]Using Pandas Lambda to compare two text strings from different columns
[英]python, compare strings in columns located in two different text files
我有2個文本文件,分別是“ animals.txt”和“ colors.txt”,其中每行中的2個字符串由一個制表符分隔。
“ animals.txt”
12345 dog
23456 sheep
34567 pig
“ colors.txt”
34567 pink
12345 black
23456 white
我想編寫以下Python代碼:
輸出1,其中包含animals.txt行和colors.txt第二列中與查詢值相對應的值(12345):
12345 dog black
23456 sheep white
34567 pig pink
output2包含colors.txt第二列中與查詢值相對應的值的列表(12345,然后是23456,然后是34567)):
black
white
pink
如果順序無關緊要,這將成為一個非常簡單的問題:
with open('animals.txt') as f1, open('colors.txt') as f2:
animals = {}
for line in f1:
animal_id, animal_type = line.split('\t')
animals[animal_id] = animal_type
#animals = dict(map(str.split,f1)) would work instead of the above loop if there are no multi-word entries.
colors={}
for line in f2:
color_id, color_name = line.split('\t')
colors[color_id] = color_name
#colors = dict(map(str.split,f2)) would work instead of the above loop if there are no multi-word entries.
#Thanks @Sven for pointing this out.
common=set(animals.keys()) & set(colors.keys()) #set intersection.
with open('output1.txt','w') as f1, open('output2.txt','w') as f2:
for i in common: #sorted(common,key=int) #would work here to sort.
f1.write("%s\t%s\t%s\n"%(i,animals[i],colors[i])
f2.write("%s"%colors[i])
您可能可以通過defaultdict
更優雅地執行此操作,在遇到特定鍵時將其追加到列表,然后在編寫時測試在輸出之前列表的長度為2,但是,我不是深信這種方法更好。
您需要使用python嗎? 如果您正在使用bash並且輸入未排序,請執行以下操作:
$ join -t $'\t' <( sort animals.txt ) <( sort colors.txt ) > output1
$ cut -f 3 output1 > output2
如果您沒有支持進程替換的外殼,請對輸入文件進行排序並執行以下操作:
$ join -t '<tab>' animals.txt colors.txt > output1
$ cut -f 3 output1 > output2
其中<tab>
是實際的制表符。 根據您的外殼,您可能可以使用ctrl-V和一個Tab鍵輸入它。 (或使用其他分隔符進行剪切。)
我會用熊貓
animals, colors = read_table('animals.txt', index_col=0), read_table('colors.txt', index_col=0)
df = animals.join(colors)
結果是:
animals.join(colors)
Out[73]:
animal color
id
12345 dog black
23456 sheep white
34567 pig pink
然后按照ID的順序將顏色輸出到文件:
df.color.to_csv(r'out.csv', index=False)
如果您無法將列標題添加到文本文件中,則可以在導入時添加它們
animals = read_table('animals.txt', index_col=0, names=['id','animal'])
假設輸入文件中的每一行的結構均與示例完全相同:
with open("c:\\python27\\output1.txt","w") as out1, \
open("c:\\python27\\output2.txt","w") as out2:
for outline in [animal[0]+"\t"+animal[1]+"\t"+color[1] \
for animal in [line.strip('\n').split("\t") \
for line in open("c:\\python27\\animals.txt","r").readlines()] \
for color in [line.strip('\n').split("\t") \
for line in open("c:\\python27\\colors.txt","r").readlines()] \
if animal[0] == color[0]]:
out1.write(outline+'\n')
out2.write(outline[outline.rfind('\t')+1:]+'\n')
我認為這將為您做到。
也許不是最優雅/快速/清晰的方法-但很短。 我認為從技術上講這是4行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.