Python 将从文件读取的真/假值转换为布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21732123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert True/False value read from file to boolean
提问by Gabriel
I'm reading a True - Falsevalue from a file and I need to convert it to boolean. Currently it always converts it to Trueeven if the value is set to False.
我正在True - False从文件中读取一个值,我需要将其转换为布尔值。目前,True即使值设置为 ,它也始终将其转换为False。
Here's a MWEof what I'm trying to do:
这MWE是我正在尝试做的事情:
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'
The file.datfile basically consists of a single string with the value Trueor Falsewritten inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.
该file.dat文件基本上由一个带有值True或False写在里面的字符串组成。这种安排看起来非常复杂,因为这是来自更大代码的最小示例,这就是我将参数读入其中的方式。
Why is flagalways converting to True?
为什么flag总是转换为True?
采纳答案by Nigel Tufnel
bool('True')and bool('False')always return Truebecause strings 'True' and 'False' are not empty.
bool('True')并且bool('False')总是返回,True因为字符串 'True' 和 'False' 不为空。
To quote a great man (and Python documentation):
引用一个伟人(和 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.
5.1. 真值测试
任何对象都可以测试真值,用于 if 或 while 条件或作为下面布尔运算的操作数。以下值被认为是错误的:
- …
- 任何数字类型的零,例如
0,0L,0.0,0j。- 任何空序列,例如,
'',(),[]。- …
所有其他值都被认为是真——所以许多类型的对象总是真。
The built-in boolfunction uses the standard truth testing procedure. That's why you're always getting True.
内置bool函数使用标准真值测试程序。这就是为什么你总是得到True.
To convert a string to boolean you need to do something like this:
要将字符串转换为布尔值,您需要执行以下操作:
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
回答by Ashwini Chaudhary
Use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('True')
True
>>> ast.literal_eval('False')
False
Why is flag always converting to True?
为什么 flag 总是转换为 True?
Non-empty strings are always True in Python.
非空字符串在 Python 中始终为 True。
Related: Truth Value Testing
相关:真值测试
If NumPy is an option, then:
如果 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)
回答by elParaguayo
I'm not suggested this as the best answer, just an alternative but you can also do something like:
我不建议将其作为最佳答案,只是一种替代方法,但您也可以执行以下操作:
flag = reader[0] == "True"
flag will be Trueid reader[0] is "True", otherwise it will be False.
标志将为Trueid reader[0] 为“True”,否则为False.
回答by ndpu
You can use dict to convert string to boolean. Change this line flag = bool(reader[0])to:
您可以使用 dict 将字符串转换为布尔值。将此行更改flag = bool(reader[0])为:
flag = {'True': True, 'False': False}.get(reader[0], False) # default is False
回答by Francesco Nazzaro
you can use distutils.util.strtobool
您可以使用 distutils.util.strtobool
>>> from distutils.util import strtobool
>>> strtobool('True')
1
>>> strtobool('False')
0
Truevalues are y, yes, t, true, onand 1; Falsevalues are n, no, f, false, offand 0. Raises ValueErrorif valis anything else.
True值为y, yes, t, true,on和1; False值是n,no,f,false,off和0。ValueError如果val是其他任何值,则引发。
回答by Gautam Joshi
Currently, it is evaluating to Truebecause the variable has a value. There is a good example found hereof what happens when you evaluate arbitrary types as a boolean.
目前,它正在评估,True因为变量有一个值。这里有一个很好的例子,说明当您将任意类型评估为布尔值时会发生什么。
In short, what you want to do is isolate the 'True'or 'False'string and run evalon it.
简而言之,您要做的是隔离'True'or'False'字符串并eval在其上运行。
>>> eval('True')
True
>>> eval('False')
False
回答by vpetersson
The cleanest solution that I've seen is:
我见过的最干净的解决方案是:
from distutils.util import strtobool
def string_to_bool(string):
return bool(strtobool(str(string)))
Sure, it requires an import, but it has proper error handling and requires very little code to be written (and tested).
当然,它需要导入,但它具有适当的错误处理,并且需要编写(和测试)的代码很少。
回答by Symon
回答by caleb
If you want to be case-insensitive, you can just do:
如果你想不区分大小写,你可以这样做:
b = True if bool_str.lower() == 'true' else False
Example usage:
用法示例:
>>> bool_str = 'False'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
False
>>> bool_str = 'true'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
True
回答by Ivan Camilito Ramirez Verdes
If your data is from json, you can do that
如果您的数据来自 json,则可以这样做
import json
json.loads('true')
True
导入json
json.loads('true')
真的

