【问题标题】:Cant convert to different data types [duplicate]无法转换为不同的数据类型[重复]
【发布时间】:2020-07-23 16:14:04
【问题描述】:

我正在尝试将包含原始数据的 .txt 文件运行到我的代码中,但我不断收到值错误。它以前可以工作,但现在我收到此错误:

ValueError:无法将字符串转换为浮点数:'.'

这是我的原始数据文件:

0.0980224609375
0.10589599609375
0.0980224609375
0.0980224609375
0.0980224609375
0.11767578125
0.130.0980224609375    --> The error is here I assume since there are 2 periods
0.10198974609375
0.10198974609375
0.0980224609375

此数据无法更改,那么如何将其从字符串转换为浮点数而不会出错?这是我的代码:

# Read and pre-process input images
n, c, h, w = net.inputs[input_blob].shape
images = np.ndarray(shape=(n, c, h, w))
for i in range(n):
    image = cv2.imread(args.input[i])
    if image.shape[:-1] != (h, w):
        log.warning("Image {} is resized from {} to {}".format(args.input[i], image.shape[:-1], (h, w)))
        image = cv2.resize(image, (w, h))
    # Swapping Red and Blue channels 
    #image[:, :, [0, 2]] = image[:, :, [2, 0]]
    # Change data layout from HWC to CHW
    image = image.transpose((2, 0, 1))  
    images[i] = image
    
    eoim = image
    eoim16 = eoim.astype(np.float16)
    
    # divide by 255 to get value in range 0->1 if necessary (depends on input pixel format)
    if(eoim16.max()>1.0):
        eoim16 = np.divide(eoim16,255)
        print(eoim16)

val = []
preprocessed_image_path = 'C:/Users/Owner/Desktop/Ubotica/IOD/cloud_detect/'
formated_image_file = "output_patch_fp"
f = open(preprocessed_image_path + "/" + formated_image_file + ".txt", 'r')
'''elem_counter = 0
for elem in eoim16:
    for elem1 in elem:
        for col in elem1:
            #f.read(int(float(formated_image_file)))
            val = float(f.readline())'''
for y in f.readlines()[0]:
    val.append(float(y))
f.close()

#print(val)
#val = np.reshape(val, (3,512,512))
val = np.ndarray(shape=(c, h, w))
#res = val

# calling the instance method using the object cloudDetector
res = cloudDetector.infer(val)
res = res[out_blob]

任何帮助将不胜感激!

【问题讨论】:

  • 0.130.0980224609375 转换为浮点数意味着什么?我和 Python 都不知道。似乎生成该文件的任何程序都有错误,因此您需要修复的错误位于代码的上游。 “我怎样才能将它从字符串转换为浮点数”的答案是——你不能。它抛出一个错误,因为这是一个真正的错误情况。
  • 如何转换0.130.0980224609375?它代表什么数字?
  • 您希望0.130.0980224609375 转换为什么浮点值?你怎么知道其他值都没有被类似地损坏,只是没有以产生语法无效数字的方式损坏?
  • @Tristan 该文件显然是由计算机生成的,而不是手动输入的,因此双句点不是拼写错误。也许它们意味着什么。您是否阅读了文件的规范?也许它讨论它。如果生成文件的计算机确实在尝试写入浮点数但插入了杂散句点,那么您真的有任何理由相信任何数字吗?将浮点文字写入文本文件很容易。它不应该有这样的错误。请注意,如果您只是删除第二个点 - 结果字符串的数字太多,不能像其他字符串一样是浮点文字。
  • 最后的观察:如果应该是0.1300980224609375 ,那么它相对于您显示的其他数字(围绕0.10)将是一个异常值。如果您通过删除第二个句点将其他双句点字符串解释为浮点数,它们是否也同样是不寻常的数字?

标签: python valueerror readlines


【解决方案1】:

您已经正确识别出了问题所在。 0.130.0980224609375 混淆了 Python,也会混淆大多数人。这是否意味着 0.13009...?这是否意味着 0.130?是2个十进制数吗?是ip地址吗? Python 没有多想,只是耸了耸肩,退出了。此代码将假定您的意思是一位小数。

def clean(s):
    while s.count(".") > 1:
        i = s.rindex(".")
        s = s[:i] + s[i+1:]
    return s

assert clean("0.130.0980224609375") == "0.1300980224609375"

【讨论】:

  • 对于这个数据,它确实意味着一位小数。还有其他出现这个双点的实例(我只是展示了发生问题的一小部分数据),所以如果有这个点的其他实例,我是否必须断言每个都清理?每次我运行程序时,新数据都会出现在 .txt 文件中,并带有类似的双点问题,所以我不知道 assert clean 是否有效,因为您必须指定数字?除非我记错了
【解决方案2】:

所以错误是因为数字中的那个额外的点,这意味着它不是一个有效的浮点数。

如果那个多余的点是错误的,而你想删除它,你可以使用:

index = y.find('.', 2) // find if there is a '.' in the string, at a position greater than 2

if(index != -1): // if there is a '.' found (find() returns -1 if the character is not found)

    y = y[:index] + y[index+1:] // reconstruct the string from the section before the . and the section after

val.append(float(y))

或者,如果您只是想忽略它:

try:
    val.append(float(y))
except ValueError:
    pass

【讨论】:

  • 你怎么知道“多余的点”可以安全删除?按照您建议的方式从非浮点文字中获取浮点文字是任意的。
  • 你是完全正确的。我认为这是错误的,你是对的,可能不是一个有效的假设
猜你喜欢
  • 2020-01-13
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
相关资源
最近更新 更多