Programing

파일에서 읽은 참 / 거짓 값을 부울로 변환

lottogame 2020. 10. 28. 07:40
반응형

파일에서 읽은 참 / 거짓 값을 부울로 변환


True - False파일에서 값을 읽고 있는데이 값을 부울로 변환해야합니다. 현재 True는 값이로 설정되어 있어도 항상로 변환합니다 False.

여기에있어 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'

file.dat파일은 기본적으로 값을 하나의 문자열로 구성 True또는 False서면 내부. 이것은 훨씬 더 큰 코드의 최소한의 예제이고 매개 변수를 읽는 방법이기 때문에 배열이 매우 복잡해 보입니다.

flag항상로 변환 True됩니까?


bool('True')그리고 bool('False')항상 반환 True문자열 '참'과 '거짓'이 비어 있지 않은 때문이다.

위대한 사람 (및 Python 문서 ) 을 인용하려면 :

5.1. 진실 가치 테스트

if 또는 while 조건에서 사용하거나 아래의 부울 연산의 피연산자로 사용하기 위해 모든 개체의 진리 값을 테스트 할 수 있습니다. 다음 값은 거짓으로 간주됩니다.

  • 모든 숫자 타입 제로 예를 들어, 0, 0L, 0.0, 0j.
  • 빈 시퀀스 (예 : '',, ()) [].

다른 모든 값은 참으로 간주되므로 여러 유형의 객체는 항상 참입니다.

내장 bool함수는 표준 진실 테스트 절차를 사용합니다. 그것이 당신이 항상 얻는 이유 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

사용 ast.literal_eval:

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

플래그가 항상 True로 변환되는 이유는 무엇입니까?

비어 있지 않은 문자열은 Python에서 항상 True입니다.

관련 : 진실 가치 테스트


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)

당신이 사용할 수있는 distutils.util.strtobool

>>> from distutils.util import strtobool

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

True값이며 y, yes, t, true, on1; False값은 n, no, f, false, off0. 발생시킵니다 ValueError경우 발은 다른 것입니다.


나는 이것을 최선의 답변으로 제안하지 않고 대안으로 제안했지만 다음과 같이 할 수도 있습니다.

flag = reader[0] == "True"

flag는 Trueid가됩니다. reader [0]은 "True"이고, 그렇지 않으면 False.


내가 본 가장 깨끗한 솔루션은 다음과 같습니다.

from distutils.util import strtobool
def string_to_bool(string):
    return bool(strtobool(str(string)))

물론 가져 오기가 필요하지만 적절한 오류 처리 기능이 있으며 작성 (및 테스트) 할 코드가 거의 필요하지 않습니다.


현재 True변수에 값이 있기 때문에 평가 중 입니다. 임의 유형을 부울로 평가할 때 발생하는 일에 대한 좋은 예가 여기 에 있습니다.

In short, what you want to do is isolate the 'True' or 'False' string and run eval on it.

>>> eval('True')
True
>>> eval('False')
False

You can use dict to convert string to boolean. Change this line flag = bool(reader[0]) to:

flag = {'True': True, 'False': False}.get(reader[0], False) # default is False

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

You can do with json.

In [124]: import json

In [125]: json.loads('false')
Out[125]: False

In [126]: json.loads('true')
Out[126]: True

pip install str2bool

>>> from str2bool import str2bool
>>> str2bool('Yes')
True
>>> str2bool('FaLsE')
False

If your data is from json, you can do that

import json

json.loads('true')

True


If you need quick way to convert strings into bools (that functions with most strings) try.

def conv2bool(arg):
   try:
     res= (arg[0].upper()) == "T"
   except Exception,e:
     res= False
   return res # or do some more processing with arg if res is false


Just to add that if your truth value can vary, for instance if it is an input from different programming languages or from different types, a more robust method would be:

flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support

And a more performant variant would be (set lookup is O(1)):

TRUTHS = set(['True','true',1,'T','t','1'])
flag = value in truths

참고URL : https://stackoverflow.com/questions/21732123/convert-true-false-value-read-from-file-to-boolean

반응형