【发布时间】:2021-02-10 18:32:06
【问题描述】:
我有一个包含很多行的输出,但我遇到的问题是它只能读取第一行和最后一行。 我还尝试将它们保存到文本文件中,结果相同 谁能告诉我如何解决这个问题?
这是我的输出:
-12 -23 0
-13 -24 0
-14 -25 0
...
-119 -130 0
-120 -131 0
-121 -132 0
这段代码给出了数据:
with open('emotion_file.txt', mode='w',newline='\n') as emotion_file:
emotion_file.write(osem)
emotion_file.close()
代码从 demofile.txt 中检索数字。它将数据转换为字段并与它们一起使用
完整代码:
import os
import sys
import numpy as np
import re
import csv
#read data
f = open("demofile.txt", "r")
lines = f.readlines()
p=1
#sys.stdout = open("results.txt", "w")
#preprocessing
for i in list(lines):
if i[0] != '<' and i[0] != '>' and i[0] != '=':
p = str(' '.join(i.split()))
print(p)
else:
#w = i[2:]
w = i.replace("=",'')
w = w.replace(">",'')
w = w.replace("<",'')
#print(w)
w = ', '.join(w.split())
y = i[2]
y=int(y)+1
c=np.array([w])
c1 = [int(i) for i in c[0].replace(" ", "").split(",")]
#transform to array
c1=np.array(c1)
frst=c1[0]
c1=np.delete(c1, 0)
n=len(c1)
sest2=c1
c1=np.array([c1]*frst)
c1=np.transpose(c1)
left1 = np.array([[(p + j) * 11 for j in range(frst)]] * n) + c1
left2 = np.array([[(p + j) * -11 for j in range(frst)]] * n) + c1
left=np.where(c1 > 0,left1 , left2)
#print(left)
left=left*-1
b=np.all(left < 0)
#6.vzorec
sest1=left
sest = np.zeros((sest1.flatten().shape[0],2))
sest[:,[0]] = sest1.T.flatten()[:,None]
sest[:,[1]] = np.tile(sest2,frst)[:,None]
sest=str(sest).replace("[",'')
sest=str(sest).replace("]",' 0')
sest = sest[:-1]
sest=str(sest).replace(".",'')
sest=str(sest).replace("\n ",'\n')
sest=str(sest).replace(" ",' ')
if b==False:
sest=str(sest).replace(" ",' ')
else:
sest=str(sest).replace(" ",' ')
sest=str(sest).replace("\n ",'\n')
sest=str(sest).lstrip()
#7.vzorec
sedem=np.transpose(left)*-1
sedem=str(sedem).replace("[",'')
sedem=str(sedem).replace("]",' 0')
sedem=str(sedem).replace(".",'')
sedem = sedem[:-1]
sedem=str(sedem).replace("\n ",'\n')
sedem=str(sedem).replace(" ",' ')
sedem=str(sedem).replace("\n ",'\n')
sedem=str(sedem).lstrip()
#8.vzorec
if frst==1:
osem='---nic-----'
else:
osem=left
osem = np.vstack([ np.c_[left[:,x], left[:,y]]
for x, y in np.c_[np.triu_indices(n=left.shape[1], k=1)] ])
osem=str(osem).replace("[",'')
osem=str(osem).replace("]",' 0')
osem = osem[:-1]
osem=str(osem).replace("\n ",'\n')
osem=str(osem).replace(" ",' ')
osem=str(osem).replace("\n ",'\n')
osem=str(osem).lstrip()
sedem=str(sedem).replace(" ",'')
#for iin osem range
p +=frst
#print(sest)
#print(sedem,)
print(osem,'\n')
with open('emotion_file.txt', mode='w',newline='\n') as emotion_file:
emotion_file.write(osem)
emotion_file.close()
变量 sest、sedem 和 osem 将字段转换为不同的形式
demofile.txt
=>11 1 2 3 4 5 6 7 8 9 10 11
【问题讨论】:
-
请添加更多细节。
-
您能向我们展示您将输出保存到文件的完整代码吗?因为我认为您正在保存的字符串
osem存在问题。 -
你试过
python myscript > output.txt -
@UtpalDutt 如果这段代码在 Windows 上运行会怎样:P
-
删除
emotion_file.close()。然后使用 body 自动执行此操作
标签: python