[英]What is the best way to print position of items in the list of strings using python
[英]Best way to print word on .txt file on right position using line and column as parameter in Python
我目前在Python中有一個程序可以讀取文本文件,但是由於幾個原因,它在保留在內存中時會丟失其格式,但是它會將行和列作為信息保留。 我將對使用此行和列信息來重現最初讀取的文件感興趣。 如果該列在空格或制表符的數量與原始數量不匹配的情況下是可以的,只要它在新文件中是一致的即可。
我想到的第一個天真的解決方案是,始終使用行和列信息始終保持一些指向行1和列1以及垃圾郵件\\n
和white spaces
指針,但是我想知道在Python中是否有更好的方法(實際上,我也不知道如何將此指針指向第一行和第一列)。
某些方法將Python中的字符串,行,列和文件作為四個參數作為參數,並且可能是一種可能的解決方案,盡管我不確定在這種情況下如果(line,column)被占用會發生什么(就我的情況而言,這永遠不會發生,因此不必擔心)。
編輯:信息存儲在一個復雜的“結構”上,但是可以說我可以提取諸如字符串列表之類的信息,其中每個字符串都有相關的行和列信息。 然后,我將使用此“方法”將每個字符串及其列和行添加到正確位置的文件中。
編輯2:唯一的假設是,當從原始文件中獲取每個單詞時,它們將以完全相同的順序發生。 也就是說,如果原始文件是“貓跳了\\ n但沒有死”,則可以預期我將使用以下字符串:“ the”,“ cat”,“ jumped”,“ and”,“沒有”,“死亡”及其相關的行和列。 在這種情況下,“ but”,“ did”,“ not”和“ die”將具有第2行而不是第1行,並且所有單詞均與它們相關的列(由於其不同的行而可能重疊或不重疊)。
謝謝。
您將需要根據行號(y)對內存中的行進行排序。 然后對於范圍為(1..N)的i,其中N =原始文件中每頁的行數,您將:
- if there are rows with that y:
- sort all rows with that y in that page using their x
- start with j = 0, and for each text chunk:
- write (x - j) spaces
- write the chunk
- set j equal to x plus the length of the chunk
- output a carriage return and continue
這將重建文本的可接受版本。 模8的微小修改甚至可以使您用制表符替換某些xj空間。
不知道它是否有效,我確定它需要一些工作。 我已經使用cat示例來模擬支持數據,然后將其放回文本中……沒有錯誤檢查,但是我認為這是它的基本內容……
import re
from operator import itemgetter
test = "The cat jumped \n but did not die"
lines = test.splitlines()
line_ref = []
for line in lines:
words = list(re.finditer(r'(\S+)', line))
line_ref.append((len(line), dict( (m.span(), m.group()) for m in words) ))
output = []
for line in line_ref:
last = max(line[1], key=itemgetter(1))[1]
textlist = [' '] * max(last, line[0])
for (start, end), word in line[1].iteritems():
textlist[start:end] = word
output.append(''.join(textlist))
print '\n'.join(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.