gpt4 book ai didi

python - 字符串 '-1' 无法转换为 float

转载 作者:太空狗 更新时间:2023-10-30 02:24:29 25 4
gpt4 key购买 nike

我尝试从使用 utf-8 编码打开的文本文件中读取大量数字。文本文件是 pdf 的复制/粘贴。问题在于负数(-1、-2 等):我删除了所有内容,因此各个字符串位如下所示:-1-2

然后我想用它们计算并用float()转换它们,但是我得到一个错误:

can't convert string to float: '-1'

我得出结论,'-' 可以被解释为一个长的 '-',无论它被称为什么,并在文本文件中手动将其替换为 '-'。现在它适用于这个单一的字符串,float() 转换它。我编写了一个小脚本,用于在文本文件中查找并替换所有 '-''-',但这没有用。

with open('text.txt', encoding='utf8') as fobj:
all = []
for line in fobj:
line = line.strip()
if '-' in line:
line.replace('-','-')
print('replaced')
all.append(line)
with open('text2.txt','w',encoding='utf8') as f:
for i in all:
print(i)
f.write(i)
f.write('\n')

为什么我可以手动将 '-' 替换为 '-' 而不能使用此脚本?感谢您的帮助。

从文本文件中截取的示例:

/ 11/3 / 2 / 0 / 0/–1 /
/ 11/5 / 0 / 2 / 0/0 / N
/ 12/3 / 1 / 0 / 0/0 /
/ 12/4 / 1 / 1 / 0/0 / NS

/ 12/4 / 4 / –1 / 0/–1 / H

/ 12/5 / 1 / 0 / 0/–1 / H

/ 12/5 / 2 / 0 / 0/-1 / H

/ 11/4 / 0 / 0 / 0/0 / H

其实可以看出倒数第二行和倒数第三行-1的区别。在这个副本中。我手动替换了最后一个。

最佳答案

您错过了作业

if '-' in line:
line = line.replace('-','-')
print('replaced')

关于python - 字符串 '-1' 无法转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53276427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com