【问题标题】:Why do I get an error printing from file data but not command line为什么我从文件数据而不是命令行打印时出错
【发布时间】:2014-11-03 23:13:43
【问题描述】:

所以在 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']

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    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'
    >>>
    

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      相关资源
      最近更新 更多