仅在未找到时附加值

时间:2015-09-30 14:27:08

标签: python

如果分类法中的分类法不在翻译中。我希望它打印152W00000X | Not Found目前所有的行都打印出Not Found。如果我删除else,我会收到超出范围的错误。

taxonomies = ['152W00000X', '156FX1800X', '200000000X', '261QD0000X', '3336C0003X', '333600000X', '261QD0000X']
translations = {'261QD0000X': 'Clinic/Center   Dental', '3336C0003X': 'Pharmacy        Community/Retail Pharmacy',  '333600000X': 'Pharmacy'}
a = 0
final = []

for nums in taxonomies:
    for i, v in translations.items():
            if nums == i:
                    data = v
                    final.append(data)
            else:
                    final.append('Not Found')

for nums in taxonomies:
    print nums, "|", final[a]
    a = a + 1

当前输出为:

152W00000X | Not Found
156FX1800X | Not Found
200000000X | Not Found
261QD0000X | Not Found
3336C0003X | Not Found
333600000X | Not Found
261QD0000X | Not Found

理想的输出是:

152W00000X | Not Found
156FX1800X | Not Found
200000000X | Not Found
261QD0000X | Clinic/Center   Dental
3336C0003X | Pharmacy        Community/Retail Pharmacy
333600000X | Pharmacy
261QD0000X | Clinic/Center   Dental
taxonomies = ['152W00000X', '156FX1800X', '200000000X', '261QD0000X', '3336C0003X', '333600000X', '261QD0000X']
translations = {'261QD0000X': 'Clinic/Center   Dental', '3336C0003X': 'Pharmacy        Community/Retail Pharmacy',  '333600000X': 'Pharmacy'}
a = 0
final = []


for nums in taxonomies:
    final.append(translations.get(nums, 'Not Found'))

for nums in taxonomies:
    print nums, "|", final[a]
    a = a + 1

1 个答案:

答案 0 :(得分:0)

我正在使用reIDVtaxo.txt拆分为两个或更多空格。除非源实际上是由制表符分隔,否则这将起作用。

import re

with open('IDVtaxo.txt') as f:
    idvtaxo = {re.split(r'\s{2,}', x)[0]: re.split(r'\s{2,}', x)[2] for x in f.read().splitlines()}

with open('taxonomies.txt') as f:
    taxonomies = f.read().splitlines()

for taxonomy in taxonomies:
    data = taxonomy.split('|')
    tranlated = idvtaxo.get(data[1], 'Not Found')
    print '%s|%s' % (taxonomy, tranlated)