在 defaultdict 中访问一个值并剥离 i 的网址部分

2024-04-26 13:22:08 发布

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

我有一个非常大的defaultdict,它在dict中有一个dict,内部dict包含来自电子邮件主体的html。我只想从内部dict中返回一个http字符串。提取它的最佳方法是什么?你知道吗

在使用regex之前是否需要将dict转换为另一个数据结构?有更好的办法吗?我对Python还是相当陌生的,很欣赏任何指点。你知道吗

例如,我的工作内容:

defaultdict(<type 'dict'>, {16: {u'SEQ': 16, u'RFC822': u'Delivered-To: 
somebody@email.com      LOTS MORE HTML until http://the_url_I_want_to_extract.com' }}

我试过的一件事就是关于芬德尔在不起作用的defaultdict上:

confirmation_link = re.findall('Click this link to confirm your registration:<br />"
(.*?)"', body)

for conf in confirmation_link:
    print conf

错误:

line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

Tags: to字符串incomhttpstring电子邮件conf
1条回答
网友
1楼 · 发布于 2024-04-26 13:22:08

只有在对字典进行相应值的迭代之后,才能使用正则表达式:

import re

d = defaultdict(<type 'dict'>, {16: {u'SEQ': 16, u'RFC822': u'Delivered-To: somebody@email.com      LOTS MORE HTML until http://the_url_I_want_to_extract.com' }}

for k, v in d.iteritems():
    #v is the dictionary that contains your html string:
    str_with_html = v['RFC822']

    #this regular expression starts with matching http, and then 
    #continuing until a white space character is hit.
    match = re.search("http[^\s]+", str_with_html)
    if match:
        print match.group(0)

输出:

http://the_url_I_want_to_extract.com

相关问题 更多 >