0

我有两个“txt”文件,其中包含多个姓名和地址或电话号码。我需要做的是读取文件,删除第一个和最后一个字母之前或之后的可能空格,并将它们组合在一个使用“电话”、“地址”和“姓名”键的字典中,如果这些值是存在于文本文件中。例如:

文件phonefile

Marco: 347 8987989
  giorgio  : 06 89786765
 Mauro B.: 3489878675
Ciro : 07897878
L. De La: 09877887

文件addrfile

Giorgio : via Verdi, 23
 M. Bianchi:Piazza Milano, 1
   L. De La : via A. Einstein, 12
 Ciro: via Pio

必须变成:

{'giorgio': {'phone': '06 89786765'},
'Marco': {'phone': '347 8987989'},
'Giorgio': {'address': 'via Verdi, 23'},
'L. De La': {'address': 'via A. Einstein, 12', 'phone': '09877887'},
'Ciro': {'address': 'via Pio', 'phone': '07897878'},
'Mauro B.': {'phone': '3489878675'},
'M. Bianchi': {'address': 'Piazza Milano, 1'}}

这是我到目前为止所尝试的:

def f_phone_addr(phonefile, addrfile):
from collections import defaultdict
e = open(phonefile)
e.readlines()
f = open(addrfile)
f.readlines()
out = defaultdict(dict)
for name, phonenumber in phonefile:
    out[name]['phone'] = phonenumber
for name, address in addrfile:
    out[name]['address'] = address           
return out

我需要一些帮助!

4

2 回答 2

1

您基本上只需要添加线路清理和处理:

我会做这样的事情:

from collections import defaultdict

def clean_line(line):
    name, _, value = line.partition(':')
    return name.strip(), value.strip()

def process_file(dic_, file, key):
    for line in file:
        name, value = clean_line(line)
        dic_[name][key] = value

def f_phone_addr(phonefile, addrfile):

    out = defaultdict(dict)
    with open(phonefile) as pf, open(addrfile) as af:
        process_file(out, pf, 'phone')
        process_file(out, af, 'address')
    return out
于 2012-10-31T11:36:34.267 回答
1
phones = dict((k.strip(), v.strip()) for k, v in
              [l.split(":") for l in
               [l.strip() for l in
                open('phonefile').read().split('\n') if l]])
addrs = dict((k.strip(), v.strip()) for k, v in
             [l.split(":") for l in
              [l.strip() for l in
               open('addrfile').read().split('\n') if l]])

dict((k, {'phone': phones.get(k), 'address': addrs.get(k)}) for k in
      set(phones.keys() + addrs.keys()))

结果

{'Ciro': {'address': 'via Pio', 'phone': '07897878'},
 'Giorgio': {'address': 'via Verdi, 23', 'phone': None},
 'L. De La': {'address': 'via A. Einstein, 12', 'phone': '09877887'},
 'M. Bianchi': {'address': 'Piazza Milano, 1', 'phone': None},
 'Marco': {'address': None, 'phone': '347 8987989'},
 'Mauro B.': {'address': None, 'phone': '3489878675'},
 'giorgio': {'address': None, 'phone': '06 89786765'}}
于 2012-10-31T11:37:38.527 回答