使用不需要的前缀从python字典输出

使用不需要的前缀从python字典输出,python,Python,(免责声明:Python和编程还是新手) 我使用Python2.7和BeautifulSoup实现了一个从网站提取数据的函数 date = soup.find('div', class_="attention-box").p.string …运行正则表达式,因为我只需要年份,而不是日期:而不是日期+月份 date = re.findall(r'(\d{4})\s+', date) …将其添加到字典中 collection['date']=date …还字典 当我尝试使用字典中的字符串打印以

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

我使用Python2.7和BeautifulSoup实现了一个从网站提取数据的函数

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']+"|" 
成功了

当我加上日期

我得到以下错误:TypeError:强制使用Unicode:需要字符串或缓冲区,找到列表

在我的函数中,我添加了
date=str(date)
并得到了一个工作输出,但在date部分得到了例如[u'2001']。在这个特定的设置中,如何在这个可视unicode表示(?)中删除这个


非常感谢。

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

如果只有一个
date
与regex使用的
find
匹配,或者您可以继续使用
findall
并使用
date[0]

列表样式访问第一个日期 首先是一种风格:你可以表现出:

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

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

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

谢谢,这对我帮助很大。我不知道
re.findall
的输出。
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'