簡體   English   中英

從 Python 腳本回溯:文字無效

[英]Traceback from a Python Script: invalid literal

簡而言之,Python 腳本應該做的是加載和計算 ASCII 類型的文件。

對於一些先前預處理過的文件,它可以正常工作而不會出錯,而對於我的,它會引發錯誤。 無論如何,看起來我的文件與它應該是的不同(輸入方面)。

Traceback (most recent call last):
  File "D:\TER\Scripts python\PuissantPDI.py", line 124, in <module>
    for i in range (42, (42+(int(type_ncols)*int(type_nrows)))):
ValueError: invalid literal for int() with base 10: 'nrows'

*它不能在任何 QGIS/ArcGIS 軟件中運行,只能從 cmd 或 IDLE 運行。

編輯

只是一小部分代碼:

import sys 

print("\nPDI Processing...\n")

''' OPTION FILE '''

with open("options_PDI.txt") as f:
    content = f.readlines()
content = [x.strip('\n') for x in content]
option= []
for elem in content:
    option.extend(elem.strip().split(" "))
f.close()

b_type_file=option[1]
b_totalstage_file=option[3]
b_function_file=option[5]
b_state_file=option[7]
b_age_file=option[9]
b_material_file=option[11]
b_occstage_file=option[13]
landcover_file=option[15]
landuse_file=option[17]
transport_file=option[19]

print("Option file loaded...\n")

''' BUILDING TYPE FILE '''

with open(b_type_file) as f:
    content = f.readlines()
content = [x.strip('\n') for x in content]
b_type= []
for elem in content:
    b_type.extend(elem.strip().split(" "))
f.close()

type_ncols=b_type[9]
type_nrows=b_type[19]
type_xll=b_type[25]
type_yll=b_type[31]
type_pixelsize=b_type[38]
type_nodata=b_type[41]

type_value=[]
for i in range (42, (42+(int(type_ncols)*int(type_nrows)))):
    type_value.append(b_type[i])

print("Building type file loaded...")

您在單個空格上拆分:

option= []
for elem in content:
    option.extend(elem.strip().split(" "))

你在某處有一個額外的空間,所以你所有的偏移量都是一對一的。

您可以通過簡單地 *刪除str.split()的參數來解決這個問題。 然后文本將被自動剝離,並在任意寬度的空白處拆分。 如果文件中有 1 或 2 或 20 個空格,則無關緊要:

with open("options_PDI.txt") as f:
    option = f.read().split()

請注意,我什至不費心將文件分成幾行或去掉換行符。

請注意,您對文件的處理仍然相當脆弱; 您期望某些值存在於某些位置。 如果您的文件包含label value樣式行,您可以將整個文件讀入字典:

with open("options_PDI.txt") as f:
    options = dict(line.strip().split(None, 1) for line in f if ' ' in line)

並使用該字典來處理各種值:

type_ncols = int(options['ncols'])

錯誤在這里很明顯。

'nrows'不能轉換為int

但是出於某種原因,您調用此type_rows不是有效整數的字符串表示形式,而是似乎包含字符串'nrows'


例如:

>>> type_rows = "nrows"
>>> int(type_rows)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'nrows'
>>> 

暫無
暫無

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

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