gpt4 book ai didi

python - 多行字典: Replace the key as per a word in value

转载 作者:行者123 更新时间:2023-12-01 05:32:00 24 4
gpt4 key购买 nike

我有一本字典,我必须根据值集中的单词替换所有键。所以我的字典是:

  { 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

最佳答案

您向 re.match 传递的 key 不正确。对于缺少的键 dict.get 返回 None,请使用 d.get('word')

>>> import re
>>> re.match('foo', None)
Traceback (most recent call last):
File "<ipython-input-43-c75223170494>", line 1, in <module>
re.match('foo', None)
File "/usr/lib/python3.3/re.py", line 156, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer

您可以使用 == 来匹配字符串或值:

if d.get('word') == 'positive':
#do something
elif d.get('word') == 'negative'
#do something else

代码:

import sys, ast
for line in sys.stdin:
d = ast.literal_eval(line)
key = list(d)[0] #dictionary with just one key.
if d[key]['word'] == 'positive':
print {'+1': d[key]}
elif d[key]['word'] == 'negative':
print {'-1': d[key]}
elif d[key]['word'] == 'neutral':
print {'0': d[key]}

输出:

{'+1': {'char': False, 'score': -8.639, 'word': 'positive'}}
{'0': {'char': False, 'score': -5.6, 'word': 'neutral'}}
{'+1': {'char': False, 'score': -8.9, 'word': 'positive'}}
{'-1': {'char': True, 'score': -2.3, 'word': 'negative'}}

关于python - 多行字典: Replace the key as per a word in value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com