如何使用 Python 舍入文本文件中的所有浮点数

How to round all floats in a text file using Python

假设您有一个包含文本和浮点数的文本文件 input.txt,但没有常规结构(例如 header、.csv 等),例如:

Banana 1.4030391
(4.245, -345.2456)
4.245 -345.2456
Hello how are you?

基于此文件,您想要生成 output.txt,其中每个浮点数都四舍五入为小数点后一位,其余内容保持不变。这会给

Banana 1.4
(4.2, -345.2)
4.2 -345.2
Hello how are you?

要在 Python 中实现此目的,您需要执行以下步骤。

  1. 打开输入文件并读取每一行

f = open('input.txt') f.readlines()

  1. 提取浮点数

如何进行?难点在于文件中没有规则结构

  1. 围绕花车

np.round(myfloat)

  1. 将行写入输出文件

...

看看这个。使用正则表达式匹配浮点数,然后替换。

import re
f = open('input.txt') 
tempstring=f.readlines()

string = ""
string = string.join(tempstring)
def check_string(string):

    temp = re.findall(r"\d+\.\d+",string)
    for i in temp:
        string=string.replace(i,str(round(float(i),1)))
    return string

output=check_string(string)
file2=open("output.txt","a+")
file2.write(output)

由于您似乎需要如何从文本文件中提取浮点数的想法,所以我只能提供一个想法。 我认为创建一个空列表并将每个单词和数字添加到其中更简单。 您可以通过在有 space 和换行符的地方剥离它来剥离文本文件中的每个项目。然后你可以使用 for 循环检查列表中的那些项目是否是浮点数。 您可以使用的函数是“.append”、“.rstrip”、“isinstance()” 下面的代码不会提取浮点数,但您可以处理它以去除文本文件中的每个项目。

mylines = []                                # Declare an empty list.
with open ('text.txt', 'rt') as myfile:    # Open txt for reading text.
    for myline in myfile:                   # For each line in the file,
        mylines.append(myline.rstrip('\n' and ' ')) # strip newline and add to list.
for element in mylines:  
    print(element)
    for item in element:
            print(item)