Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

python - How do you look for the index of a string in a large file and ask for a string at a certain index?

I am working on a program (Python) which needs to look through a large text file with a bunch of words in it.

The file is around 4.03 MB (over 4 million characters) of words seperated with a new line. (This is what I mean)

What I want to do is look line by line in the file for a specific word then get the "index" of it. Also I want to be able to reach into the file and get a specific word by using the index without looking through the file.

How would I make this happen (preferably a very efficient code since my program will be looking through the file quite frequently)?

question from:https://stackoverflow.com/questions/65914342/how-do-you-look-for-the-index-of-a-string-in-a-large-file-and-ask-for-a-string-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By the index, do you mean to position of the word in the file? This will find the position of the specified text in a file...

file = open("text.txt","r")
text = file.read()
print(text.index("word"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...