gpt4 book ai didi

python - 为什么从文件数据打印时出现错误,但从命令行打印时却没有

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:50 24 4
gpt4 key购买 nike

因此在 Python 命令行中:

th = {u'category': u'Hair Color'}
>>> print q
{u'category': u'Hair Color'}
>>> print th['category']
Hair Color

很好,这有效。但现在假设我有一个名为 ant.txt 的文件,其内容相同:

{u'category': u'Hair Color'}

我想再次像上面一样打印对象和成员。

>>> f = open('ant.txt')
>>> q = f.read()
>>> print q
{u'category': u'Hair Color'}
>>> print q['category']
Traceback (most recent call last):
File "<pyshell#230>", line 1, in <module>
print q['category']
TypeError: string indices must be integers, not str

我知道错误的原因是我没有指定整数。但是为什么当我从文件加载时会出现错误,而不是在命令行创建时出现错误?

从文件读取时,我需要对 print q['category'] 进行哪些更改?

最佳答案

f.read() 读入文件的内容并将其作为 string 对象返回。您可以通过删除 print 并只需输入 q 来亲自查看这一点:

>>> q
"{u'category': u'Hair Color'}"
>>> print q # 'print' removes the quotes on each end.
{u'category': u'Hair Color'}
>>>

要将字典的字符串表示形式转换为实际的字典对象,可以使用 ast.literal_eval :

import ast
q = ast.literal_eval(f.read())

下面是一个演示:

>>> import ast
>>> q = "{u'category': u'Hair Color'}" # Data read from file
>>> type(q)
<class 'str'>
>>> q = ast.literal_eval(q)
>>> q
{'category': 'Hair Color'}
>>> type(q)
<class 'dict'>
>>> q['category']
'Hair Color'
>>>

关于python - 为什么从文件数据打印时出现错误,但从命令行打印时却没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724999/

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