我想减去文件的两个连续行。例如:
我有一个包含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
完成
〜
〜
答案 0 :(得分:0)
实际上,您可以将结果直接从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