2012-10-31 16 views
0

我有两个包含多个名称和地址或电话号码的“txt”文件。我需要做的是读取文件,在第一个和最后一个字母之前或之后删除可能的空格,并将它们合并到一个使用“电话”,“地址”和“名称”键的单个词典中,如果这些值是出现在文本文件中。 例如:将两个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 

我需要一些帮助,请!

+0

你是什么确切题? – Kai

+0

@ user714965问题是“如何有效地将两个文本文件合并成一个字典,根据其内容正确分类名称,电话号码和地址?” – test123

+0

你已经发布了一些代码。该代码有什么问题?是否存在您想要询问的错误,或者您是否希望有人为您提供一些可以复制/粘贴的代码? – Kai

回答

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 
+0

我得到“NameError:全局名称”out'未定义“错误。当我尝试将“out”定义为“{}”时,我得到此代码:line 69,in process_file out [name] [key] = value KeyError:'Marco'“ – test123

+0

@ test123:fixed。从基本的Python教程开始 – SilentGhost

+0

这就是为什么我仍然只是一个学生... :(无论如何。 – test123

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'}} 
相关问题