簡體   English   中英

如何在python上的文件中減去兩行乘以兩行的組?

[英]How can I subtract groups of two by two rows of a file on python?

我想減去一個文件的兩個連續行。 例如:

我有一個包含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}' 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內部寫入文件中。 例如這樣的:

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM