从python字典输出带有不需要的前缀

时间:2013-03-13 20:36:21

标签: python

(免责声明:对Python和编程来说还是新手)

我使用Python 2.7和Beautiful Soup来提取从网站中提取数据的功能......

date = soup.find('div', class_="attention-box").p.string

...运行正则表达式,因为我只需要年份,而不是日期:而不是日期+月......

date = re.findall(r'(\d{4})\s+', date)

...将其添加到字典中......

collection['date']=date

...并返回字典。

当我尝试使用字典中的字符串打印以下内容(我正在为wiki创建模板)

print "|" + collection['URL'] + "|" + collection['title'] + "|" + collection['name']+"|" 

它有效。

当我添加 date

print "|" + collection['URL'] + "|" + collection['title'] + "|" + collection['name']+"|" + collection['date'] + "|" 

我收到以下错误: TypeError:强制转换为Unicode:需要字符串或缓冲区,找到列表

在我的功能中,我添加了date = str(date)并获得了一个正常工作的输出,我得到了日期部分中的 [u' 2001'] 。如何在此特定设置中以此可视化unicode表示(?)删除此内容?

非常感谢。

2 个答案:

答案 0 :(得分:1)

findall正在返回一个集合(一个python列表)。

如果只有一个date匹配该正则表达式使用find,或者您可以继续使用findall并使用date[0]访问第一个日期

答案 1 :(得分:1)

列表样式

首先是风格的东西:你可以代表这个:

print "|" + collection['URL'] + "|" + collection['title'] + "|" + collection['name']+"|" + collection['date'] + "|" 

这样:

print "|".join([a[x] for x in ('URL', 'title', 'name', 'date')])

演示:

In : a
Out: {'URL': 'example.com', 'date': '2013-03-13', 'name': 'Mel', 'title': 'Foo!'}

In : [a[x] for x in ('URL', 'title', 'name', 'date')]
Out: ['example.com', 'Foo!', 'Mel', '2013-03-13']

In : "|".join([a[x] for x in ('URL', 'title', 'name', 'date')])
Out: 'example.com|Foo!|Mel|2013-03-13'

使用re

第二点是re.findall返回所有匹配的数组。您可能希望将匹配设置为re.search(...),使用result.group()检索,或者如果要在找到多个匹配项时进行错误检查,请使用re.finditer。您也可以获取re.findall的第一个值,但考虑到其他两个选项,这似乎效率低下。