【问题标题】:How to Print Command output.txt line by line [duplicate]如何逐行打印命令 output.txt [重复]
【发布时间】:2019-06-13 19:40:01
【问题描述】:

如何打印读取数字列表中小数位和空格的输出文件。如果逗号和数字之间的小数位数多于或少于 2 位和/或空格,则该数字无效并打印在输出文本文件中。如果它有 2 个小数位并且数字和逗号之间没有空格,那么它是一个有效数字,并且 I 将打印在输出文本文件中。 输出文件: VALID #只有当float有两位小数且没有空格时才有效 10.34,456.78

INVALID #仅当浮点数大于或小于两位小数或整数或数字和逗号之间有空格时才无效 10.345, 45.678(空白,有 3 个 sig figs)

创建一个以逗号分隔的数字文件 文本文件:

1,2.12,3.123

1,1.00

有多少数字通过了 VALID sigfig 过滤器。

from functools import reduce
res = 0
outfile = "output2.txt"
baconFile = open(outfile,"wt")
index = 0
invalid_string = "INVALID"
valid_string = "VALID"
for line in open("file.txt"):               #for loop with variable line defined and using open() function to open the file inside the directory

    for line in open("file.txt"):               #for loop with variable line defined and using open() function to open the file inside the directory

        carrera = ''
        index = index +1                            #adds 1 for every line if it finds what the command wants

        print("Line {}: ".format(index))
        baconFile.write("Line {}:  ".format(index))

    with open('file.txt') as file:
        number_list = file.readline().strip().split(',')
        for line in number_list:
            if len(line.split('.')[-1]) == 2:
                #res += 1
##              print("VALID")

                carrera = valid_string 
            if len(line.split('.')[-1]) != 2:
                #res += 1
                carrera = invalid_string  

            print (carrera)
            baconFile.write(carrera + " ")
#print(res)
baconFile.close()


#For example, my list looks like this from my text file:
1,2.12,3.123
#Then it print out this to my output text file

output (decimal places from each number):
Line 1: INVALID VALID INVALID
#However, if my list from my text file is like this:
1,2.12,3.123
1,1.00
#Then it print out this to my output text file
output: 
Line 1: Line 2:   INVALID 
VALID
INVALID
Line 3: Line 4:   INVALID
VALID
INVALID
#How do I get it to print out like this to my output text file:
Line 1: INVALID VALID INVALID
LINE 2: INVALID VALID

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在你的第一个例子中:

    if '.' in number:
        res += len(number.split('.')[-1])
    

    您正在计算有效位数,然后将该数字添加到res。因此,您当然会得到所有项目的有效数字总数。

    如果您只想计算有多少项恰好有两位有效数字,请尝试以下方法:

    if '.' in number:
        if len(number.split('.')[-1]) == 2:
            res += 1
    

    【讨论】:

    • 这很好,我更新了我的代码谢谢!
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2012-12-18
    • 2011-12-05
    • 2019-07-03
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多