【发布时间】:2013-11-29 16:32:44
【问题描述】:
我有一本字典,我必须根据值集中的单词替换所有键。所以我的字典是:
{ 23: {'score': -8.639, 'char': False, 'word': 'positive'} }
{ 56: {'score': -5.6, 'char': False, 'word': 'neutral'} }
{ 89: {'score': -8.9, 'char': False, 'word': 'positive'} }
{ 34: {'score': -2.3, 'char': Tru, 'word': 'negative'} }
如果字典的值部分,即关键字是正数,那么它应该用 +1 替换键 23,对于中性,用 0 替换键 56,对于负数,用 -1 替换键 34。
输出将如下所示:
{ +1: {'score': -8.639, 'char': False, 'word': 'positive'} }
{ 0: {'score': -5.6, 'char': False, 'word': 'neutral'} }
{ +1: {'score': -8.9, 'char': False, 'word': 'positive'} }
{ -1: {'score': -2.3, 'char': Tru, 'word': 'negative'} }
这是我的代码:
for n, line in enumerate(sys.stdin,1):
d = ast.literal_eval(line)
items = d.values()[0].items()
if re.match("positive",d.get('sentimentoftweet')):
n = str.replace(str(n),"+1")
else:
n = str.replace(str(n),"0")
它不工作并给我这个错误:
Traceback (most recent call last):
File "./linear.py", line 33, in <module>
for thing in d:
File "./linear.py", line 22, in gen_with_appropriate_name
if re.match("positive",d.get('sentimentoftweet')):
File "/usr/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
【问题讨论】:
-
sentimentoftweet在您的输入数据中根本不存在。 -
是否需要通过标准输入传递输入?将数据存储为实际的字典对象并将其传递给函数不是更容易吗?
标签: python regex string dictionary replace