将从文件读取的真/假值转换为布尔值

2024-04-19 15:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从文件中读取一个True - False值,需要将其转换为布尔值。当前,它总是将其转换为True,即使该值设置为False

以下是我要做的一件事:

with open('file.dat', mode="r") as f:
    for line in f:
        reader = line.split()
        # Convert to boolean <-- Not working?
        flag = bool(reader[0])

if flag:
    print 'flag == True'
else:
    print 'flag == False'

file.dat文件基本上由一个单独的字符串组成,其中的值是TrueFalse。这种排列看起来非常复杂,因为这是一个非常大的代码的最小示例,这是我如何将参数读入其中的。

为什么flag总是转换成True


Tags: infalsetrueformodeaswithline
3条回答

你可以使用^{}

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True值是yyesttrueon1False值是nnoffalseoff0。如果val是其他值,则引发ValueError

bool('True')bool('False')始终返回True,因为字符串'True'和'False'不是空的。

引用一位伟人(和Python)的话:

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].

All other values are considered true — so objects of many types are always true.

内置的^{}函数使用标准的真值测试过程。这就是为什么你总是得到True

要将字符串转换为布尔值,需要执行以下操作:

def str_to_bool(s):
    if s == 'True':
         return True
    elif s == 'False':
         return False
    else:
         raise ValueError # evil ValueError that doesn't tell you what the wrong value was

使用^{}

>>> import ast
>>> ast.literal_eval('True')
True
>>> ast.literal_eval('False')
False

Why is flag always converting to True?

在Python中,非空字符串始终为True。

相关:Truth Value Testing


如果NumPy是一个选项,那么:

>>> import StringIO
>>> import numpy as np
>>> s = 'True - False - True'
>>> c = StringIO.StringIO(s)
>>> np.genfromtxt(c, delimiter='-', autostrip=True, dtype=None) #or dtype=bool
array([ True, False,  True], dtype=bool)

相关问题 更多 >