I am quiet new to python, and I want to extract one page from a text file. Each page starts with a unique line and ends with '//'. And I want to find a way to return a certain page knowing the unique line associated with it. Do you know what tools can I use?
You could split
the file by "//"
and then split
by "\\n"
to obtain the first line, then creating a dictionary associating a line with a page.
header_to_page = {}
with open("file.txt", "r") as f:
content = f.read()
pages = content.split("//")
for page in pages:
lines = page.split("\n")
header_to_page[lines[0]] = "".join(lines[1:])
print header_to_page["example line"]
You can load the textfile and use split for the "//"
file = open(“testfile.txt”, “r”)
contents = file.read()
pages = contents.split("//")
pages is now a list and you can indicate which index you want to get
print(pages[0])
Hi try splitting the text in to a list:
import pickle
text= "hello this is a unique line. and it will end with // this should be
the other line and it also ends with // a third line just for good mesure//"
pickle.dump(text, open("text.txt","wb"))
page = pickle.load(open("text.txt","rb")).split("//")[0]
print(page)
and then just index the page you want in this line:
page = pickle.load(open("text.txt","rb")).split("//")[0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.