[英]Python: Get the line and column number of string index?
假設我有一個正在操作的文本文件。 像這樣的東西(希望這不是太難以理解):
data_raw = open('my_data_file.dat').read()
matches = re.findall(my_regex, data_raw, re.MULTILINE)
for match in matches:
try:
parse(data_raw, from_=match.start(), to=match.end())
except Exception:
print("Error parsing data starting on line {}".format(what_do_i_put_here))
raise
請注意,在異常處理程序中有一個名為what_do_i_put_here
的變量。 我的問題是:如何分配給該名稱,以便我的腳本將打印包含我正在嘗試使用的“壞區域”開頭的行號? 我不介意重新閱讀文件,我只是不知道我會做什么......
我寫了這個。 它未經測試且效率低下,但確實有助於我的異常消息更加清晰:
def coords_of_str_index(string, index):
"""Get (line_number, col) of `index` in `string`."""
lines = string.splitlines(True)
curr_pos = 0
for linenum, line in enumerate(lines):
if curr_pos + len(line) > index:
return linenum + 1, index-curr_pos
curr_pos += len(line)
我什至沒有測試過列號是否准確。 我沒有遵守YAGNI
這里有一些更清晰的東西,在我看來,比你自己的答案更容易理解:
def index_to_coordinates(s, index):
"""Returns (line_number, col) of `index` in `s`."""
if not len(s):
return 1, 1
sp = s[:index+1].splitlines(keepends=True)
return len(sp), len(sp[-1])
它的工作方式與您自己的答案基本相同,但是通過使用字符串切片splitlines()
實際上可以計算您需要的所有信息,而無需任何后期處理。
必須使用keepends=True
來為行尾字符提供正確的列數。
唯一的額外問題是空字符串的邊緣情況,可以很容易地由保護子句處理。
我在 Python 3.8 中對其進行了測試,但它可能在大約 3.4 版之后正常工作(在某些舊版本中len()
計算代碼單元而不是代碼點,我認為它會因包含 BMP 之外的字符的任何字符串而中斷)
列索引從 0 開始,因此您需要在代碼的最后從 len(sp[-1]) 中提取 1 以獲得正確的列值。 此外,如果字符串的長度為 0 或字符串太短而無法適應索引,我可能會返回 None (而不是“1.1” - 這也是不正確的,因為它應該是“1.0”......)。 否則,這是一個出色而優雅的解決方案Tim。
def index_to_coordinates(txt:str, index:int) -> str:
"""Returns 'line.column' of index in 'txt'."""
if not txt or len(txt)-1 < index:
return None
sp = txt[:index+1].splitlines(keepends=True)
return (f"{len(sp)}.{len(sp[-1])-1}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.