Python使用字典、文件

2024-04-25 02:28:54 发布

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

我有这个密码:

def merge_new_old_urls(urls_list, urls_file_path):
    url_dict = {}
    try:
        with open(urls_file_path, "r") as f:
            data = f.readlines()
        for line in data:
            #read what is already in file
            url_dict = { line.split()[0]: int(line.split()[1])}
        for new in urls_list:
            for key in url_dict.keys():
                if new == key:
                    print 'found'
                    url_dict[key] += 1
                else:
                    url_dict[new] = 1

    except IOError:
        logging.critical('no files to read from %s' % urls_file_path)
        raise IOError('no files to read from %s' % urls_file_path)
    return url_dict

这应该从文件中读取数据,并将其与新的数据列表合并,计算重复的次数。包含旧URL的文件如下所示:

http://aaa.com 1
http://bbb.com 2
http://ccc.com 1

如果新的url列表包含http://aaa.comhttp://bbb.com,dict应该是:

'http://aaa.com':2
'http://bbb.com':3
'http://ccc.com':1

但我的代码不能正常工作。有人能治好吗?你知道吗


Tags: pathkeyincomhttpurlnewfor
1条回答
网友
1楼 · 发布于 2024-04-25 02:28:54

每次通过循环重新定义url_dict

url_dict = {line.split()[0]: int(line.split()[1])}

将条目添加到字典中:

for line in data:
    key, val = line.split()
    if key in url_dict:
        url_dict[key] += val
    else:
        url_dict[key] = val

而您在字典中的搜索是完全没有必要的,您可以使用与上面相同的语法:

for key in urls_list:
    if key in url_dict:
        url_dict[key] += val
    else:
        url_dict[key] = val  

最后,您不应该在try中包装太多内容:

try:
   with open(urls_file_path, "r") as f:
        data = f.readlines()
except IOError:
    logging.critical('no files to read from %s' % urls_file_path)
    raise IOError('no files to read from %s' % urls_file_path)
else:
    # rest of your code

相关问题 更多 >