我有一個 python 腳本,它根據距地面的距離和角度計算樹的高度,但是,盡管腳本運行沒有錯誤,但我的高度列是空的。另外,我不想使用熊貓,如果可能的話,我想保持“開放”的方法,然后再有人建議以不同的方式去做。任何幫助都會非常感謝。似乎整個腳本運行良好,并且完成了我需要的所有操作,直到“for row in csvread:”塊。這是我當前的腳本:
#!/usr/bin/env python3
# Import any modules needed
import sys
import csv
import math
import os
import itertools
# Extract command line arguments, remove file extension and attach to output_filename
input_filename1 = sys.argv[1]
input_filename2 = os.path.splitext(input_filename1)[0]
filenames = (input_filename2, "treeheights.csv")
output_filename = "".join(filenames)
def TreeHeight(degrees, distance):
"""
This function calculates the heights of trees given distance
of each tree from its base and angle to its top, using the
trigonometric formula.
"""
radians = math.radians(degrees)
height = distance * math.tan(radians)
print("Tree height is:", height)
return height
def main(argv):
with open(input_filename1, 'r') as f:
with open(output_filename, 'w') as g:
csvread = csv.reader(f)
print(csvread)
csvwrite = csv.writer(g)
header = csvread.__next__()
header.append("Height.m")
csvwrite.writerow(header)
# Populating the output csv with the input data
csvwrite.writerows(itertools.islice(csvread, 0, 121))
for row in csvread:
height = TreeHeight(csvread[:,2], csvread[:,1])
row.append(height)
csvwrite.writerow(row)
return 0
if __name__ == "__main__":
status = main(sys.argv)
sys.exit(status)
uj5u.com熱心網友回復:
查看您的代碼,我認為您大部分時間都在那里,但在讀/寫行時有點困惑:
# Populating the output csv with the input data
csvwrite.writerows(itertools.islice(csvread, 0, 121))
for row in csvread:
height = TreeHeight(csvread[:,2], csvread[:,1])
row.append(height)
csvwrite.writerow(row)
看起來您正在讀取第 1 行到第 121 行并將它們寫入新檔案。 然后,您嘗試在第二遍中迭代您的 CSV 閱讀器,計算高度,然后將該計算值附加到行的末尾,并在完整的第二遍中寫入您的 CSV。
如果這是真的,那么您需要了解 CSV讀取器和寫入器并非旨在像那樣“從左到右”作業:讀寫這些列,然后讀寫這些列......不。
它們都“自上而下”地作業,處理行。
我建議,為了讓這個作業:在一個回圈中迭代每一行,并且對于每一行:
- 讀取
row計算高度所需的值 - 得到計算的高度
- 將新計算的添加到原始
- 寫
...
header = next(csvread)
header.append("Height.m")
csvwrite.writerow(header)
for row in csvread:
degrees = float(row[1]) # second column for degrees?
distance = float(row[0]) # first column for distance?
height = TreeHeight(degrees, distance)
row.append(height)
csvwrite.writerow(row)
我做了一些改變:
- 我替換
header = csvread.__next__()為header = next(csvread). 至少在標準庫中,通常不鼓勵 呼叫以開頭_或通常不鼓勵的東西。是內置功能,可讓您正確安全地通過.__next(<iterator>)<iterator> - 添加
float()了從 CSV 讀取的文本值的轉換
此外,據我所知,,2/,1是不正確的下標/切片表示法語法。您沒有收到任何錯誤,因為閱讀器已經完成/已從islice()呼叫中筋疲力盡,因此您的程式實際上從未進入for row in csvread:回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413671.html
標籤:
