python,比较位于两个不同文本文件中的列中的字符串

2024-04-25 05:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件,”动物.txt“和”颜色.txt“如下所示,每行中的2个字符串用制表符分隔。在

““动物.txt““

12345  dog

23456  sheep

34567  pig

““颜色.txt““

^{pr2}$

我想编写Python代码:

  1. “中的每一行”动物.txt“获取第一列中的字符串(12345、23456、34567)
  2. 将此字符串与“”中第一列中的字符串进行比较txt颜色““
  3. 如果找到匹配项(12345==12345,等等),它将写入两个输出文件:

output1,包含动物.txt+的第二列中的值颜色.txt对应于查询值(12345):

12345 dog   black
23456 sheep white
34567 pig   pink 

output2包含的第二列中的值的列表颜色.txt对应于查询值(12345、23456、34567)):

black
white
pink

Tags: 文件字符串代码txt颜色制表符blackwhite
3条回答

你需要使用python吗?如果您正在使用bash并且输入未排序,请执行以下操作:

$ join -t $'\t' <( sort animals.txt ) <( sort colors.txt ) > output1
$ cut -f 3 output1 > output2

如果没有支持进程替换的shell,请对输入文件进行排序并执行以下操作:

^{pr2}$

其中<tab>是实际的制表符。根据您的shell,您可以使用ctrl-V和tab键来输入它。(或对剪切使用不同的分隔符。)

我会用熊猫

animals, colors = read_table('animals.txt', index_col=0), read_table('colors.txt', index_col=0)
df = animals.join(colors)

结果:

^{pr2}$

然后按id的顺序将颜色输出到文件:

df.color.to_csv(r'out.csv', index=False)

如果无法将列标题添加到文本文件,则可以在导入时添加它们

animals = read_table('animals.txt', index_col=0, names=['id','animal'])

如果顺序无关紧要,这就成了一个相当简单的问题:

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,但是,我不认为这种方法更好。在

相关问题 更多 >