我想讀一系列的座標以及它們的準確性轉化爲三角函數來提供三角座標。我已經能夠使用Python來創建一個包含座標列表中爲每個三角.txt的文件即將數據讀入Python一行一行地作爲列表
[(-1.2354798, 36.8959406, -22.0), (-1.245124, 36.9027361, -31.0), (-1.2387697, 36.897921, -12.0), (-1.3019762, 36.8923956, -4.0)]
[(-1.3103075, 36.8932163, -70.0), (-1.3017684, 36.8899228, -12.0)]
[(-1.3014139, 36.8899931, -34.0), (-1.2028006, 36.9180461, -54.0), (-1.1996497, 36.9286186, -67.0), (-1.2081047, 36.9239936, -22.0), (-1.2013893, 36.9066869, -11.0)]
每個那些將座標和準確性的一組喂到三角功能。文本文件按行分開。
這是三角功能我想讀的文本文件導入:
def triangulate(points):
"""
Given points in (x,y, signal) format, approximate the position (x,y).
Reading:
* http://stackoverflow.com/questions/10329877/how-to-properly-triangulate-gsm-cell-towers-to-get-a-location
* http://www.neilson.co.za/?p=364
* http://gis.stackexchange.com/questions/40660/trilateration-algorithm-for-n-amount-of-points
* http://gis.stackexchange.com/questions/2850/what-algorithm-should-i-use-for-wifi-geolocation
"""
# Weighted signal strength
ws = sum(p[2] for p in points)
points = tuple((x,y,signal/ws) for (x,y,signal) in points)
# Approximate
return (
sum(p[0]*p[2] for p in points), # x
sum(p[1]*p[2] for p in points) # y
)
print(triangulate([
(14.2565389, 48.2248439, 80),
(14.2637736, 48.2331576, 55),
(14.2488966, 48.232513, 55),
(14.2488163, 48.2277972, 55),
(14.2647612, 48.2299558, 21),
]))
當我測試與它的工作原理上面打印語句的功能。但是,當我嘗試從文本文件中的數據加載到功能如下」
with open(filename, 'r') as file:
for points in file:
triangulation(points)
我得到的錯誤:IndexError: string index out of range
我明白,這是因爲它沒有被讀取作爲一個名單,但作爲字符串,但當我嘗試將其轉換爲列表對象points = list(points)
它也不被識別爲不同的座標列表。我的問題是我應該如何讀取文件到python中,以便它被轉換爲在三角函數內工作
您的文本文件按原樣讀取,Python不知道您的行的結構。它沒有看到列表和元組。一個快速的解決辦法是做'data = eval(points)',但我強烈建議不要這樣做,因爲'eval'通常是不鼓勵的。相反,您應該重新格式化您的文件以包含JSON或任何其他機器可讀格式。 – FMCorz