試圖索引文本檔案(格式化為每行一個句子)......但字符位置似乎在某些時候傾斜......在下面的示例中,這發生在第 19 行/句子。
首先我檢查找到位置,然后我讀取相同的范圍,但計算出的范圍(279)大了 4 個字符!
知道可能是什么原因嗎?
start = fh.tell()
line = fh.readline()
end = fh.tell()
print(f"line:{i},pos:{start}-{end} : {end-start}\n{line}")
line:19,pos:2703-2982 : 279
Many revolutionaries of the 19th century such as William Godwin ( 1756 – 1836 ) and Wilhelm Weitling ( 1808 – 1871 ) would contribute to the anarchist doctrines of the next generation but did not use " anarchist " or " anarchism " in describing themselves or their beliefs .
fh.seek(2703)
print(fh.read(279))
Many revolutionaries of the 19th century such as William Godwin ( 1756 – 1836 ) and Wilhelm Weitling ( 1808 – 1871 ) would contribute to the anarchist doctrines of the next generation but did not use " anarchist " or " anarchism " in describing themselves or their beliefs .
The

uj5u.com熱心網友回復:
tell在面向文本的檔案上沒有記錄的含義。它正式是一個不透明的 cookie,可以與 一起使用seek,否則不能指望它有任何意義。這提供了將使用中的編碼所需的附加資訊編碼到 cookie 中的靈活性,即使它將多個位元組表示為每個字符一個位元組的編碼檔案,它也可能與讀取的字符數不同,因為 line - 結束翻譯。類似地,在具有可變長度字符編碼的編碼中,位元組位置不會對應于字符計數。根據檔案:
tell()將當前流位置作為不透明數字回傳。該數字通常不代表底層二進制存盤中的位元組數。
簡而言之,除了將其傳遞回seek呼叫之外,您不能也不應該依賴產生的數字來獲得對您有用的任何含義。該值是一個實作細節。
sten:這似乎可行..將進行更多測驗以確保,謝謝這是救生員..將立即批準答案;)
更簡單的方法是做 file.seek(ix[pos]) 然后做 file.readline()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505074.html
