【问题标题】:How can I subtract groups of two by two rows of a file on python?python - 如何在python上将文件的两行减去两行?
【发布时间】:2019-08-15 03:25:08
【问题描述】:

我想减去一个文件的两个连续行。例如:

我有一个包含 4,000,000 行的文件,其数据如下:

    2345  345.67
    2344  245.34
    45678  331.45
    45679  339.32
    7654   109.42
    7655   250.78

所以我想减去两个连续的行(第 2 列)并打印绝对结果,只要结果大于或等于 60。减法将是两行乘两行,并打印到第 1 列的第一个值. 我的意思是,我想要这样的结果:

    2345   100.13
    7654   141.36

我尝试在 bash 中执行此操作,但速度太慢了,我想在 python 中执行此操作,但我不知道如何操作,我是 python 新手。如何直接读取我的文件以及如何使用 python 模块?我已经阅读过数据框和 abs 可以帮助我,但是,如何?可以指导一下吗?

非常感谢。

x=1

而 [ $x -ge 2 ]

a=sed -n '1,2p' file.dat| awk 'NR>1{print $1-p} {p=$1}'

echo $a >> results.dat

grep -v "$a" file.dat > file.o

mv file.o file.dat

完成

~
~

【问题讨论】:

    标签: python numbers rows absolute


    【解决方案1】:

    您实际上可以在 Python 中将结果直接写入文件。比如这样:

    # import regular expression module of python
    import re
    # open file (replace data.txt with input file name and out.txt with the output file name)
    with open('data.txt', 'r') as f, open('out.txt', 'w') as o:
        # read the first line (i=0) manually
        currentLine = re.findall('\d+\.?\d*', f.readline())
        # index i starts with 0 and refers to the currentLine, s.t.
        # prevLine
        # currentLine [i=0]
        # prevLine [i=0]
        # currentLine [i=1]
        # therefore we only look at every second iteration
        for i,line in enumerate(f.readlines()):
            # set the previous line to the current line
            prevLine = currentLine
            # extract numbers
            currentLine = re.findall('\d+\.?\d*', line)
            if i%2==0: # look only at every second iteration (row 1 - row 2; row 3 - row 4; etc.)
                # calculate the absolute difference between rows i and i+1, i.e. abs((i,0)-(i+1,1))
                sub = abs(float(prevLine[1])-float(currentLine[1]))
                # if this absolute difference is >= 60, print the result
                if sub>=60:
                    outputLine = "%s %s"%(str(prevLine[0]), str(sub))
                    print(outputLine)
                    o.write(outputLine+"\n") # write the line to the file 'out.txt'
    

    因此,您的数据的输出将是:

    2345 100.33000000000001
    7654 141.36
    

    【讨论】:

    • 谢谢肖恩,但是,我怎么能适应它,例如:1 和 2 行之间的减法,然后读取 3 和 4 行,然后读取 4 和 5 行,等等。我不需要阅读 1 和 2、2 和 3...等。我尝试了更改:prevLine = currentLine+1 但我有这个错误: Traceback (last recent call last): File "prueba.py", line 10, in prevLine = currentLine+1 TypeError: can only concatenate list (不是“int”)列出你能指导我吗?非常感谢
    • 我明白了。我已经相应地更新了答案。语句 prevLine = currentLine + 1 抛出错误的原因是您试图将整数 1 添加到列表对象 currentLine
    • 非常感谢肖恩。这就是我要找的。干杯。
    猜你喜欢
    • 2011-07-12
    • 2017-09-29
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2018-04-17
    相关资源
    最近更新 更多