gpt4 book ai didi

python - 在文本文件中用整数替换 float

转载 作者:行者123 更新时间:2023-12-04 10:28:10 25 4
gpt4 key购买 nike

我想在几个文本文件中找到并用整数替换浮点数。
我要转换的每个文本文件有一个浮点值。它总是在特定关键字之后,并且必须乘以 10.000。
例如浮点数 1.5 应该变成整数 15.000
1.5 之后的其他浮点数不必更改

def edit(file):
with open(file, 'r') as f:
filedata = f.read()
for line in filedata:
if "keyword" in line:
filedata = filedata.replace(re.search(r"\d+\.\d+", line).group(), str(10000*re.search(r"\d+\.\d+", line).group()))
with open(file, 'w') as f:
f.write(filedata)

我试图用正则表达式替换浮点数。但这不起作用

示例文件提取
abcdef 178 211 208 220    
ghijkl 0 0 0 0
keyword 1.50 1.63 1.56 1.45

最佳答案

您可以使用 lines = filedata.split("\n") 遍历行.小心,因为filedata是一个包含整个文件的大字符串。你什么时候做的for line in filedata ,您遍历文件的每个字符...

我还使用了另一种方法(没有 regex )来查找数字并更改它们。

def edit(file):
with open(file, "r") as f:
filedata = f.read()
lines = filedata.split("\n") # list of lines
for index, line in enumerate(lines):
if "keyword" in line:
words = line.split() # ['keyword', '1.50', '1.63', '1.56', '1.45']
for i, w in enumerate(words):
try:
# transform number to float, multiply by 10000
# then transform to integer, then back to string
new_word = str(int(float(w)*10000))
words[i] = new_word
except:
pass
lines[index] = " ".join(words)
new_data = "\n".join(lines) # store new data to overwrite file


with open(file, "w") as f: # open file with write permission
f.write(new_data) # overwrite the file with our modified data

edit("myfile.txt")

输出 :
# myfile.txt
abcdef 178 211 208 220
ghijkl 0 0 0 0
keyword 15000 16299 15600 14500

编辑 : 更紧凑的方式
def edit(file):
with open(file, "r") as f:
filedata = f.read()
line = [x for x in filedata.split("\n") if "keyword" in x][0]
new_line = line
for word in line.split():
try: new_line = new_line.replace(word, str(int(float(word)*10000)))
except: pass
with open(file, "w") as f: # open file with write permission
f.write(filedata.replace(line, new_line)) # overwrite the file with our modified data

edit("myfile.txt")

关于python - 在文本文件中用整数替换 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60545654/

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