Skip to content Skip to sidebar Skip to footer

How To Find A String In A Txt File

how do i find a string or a list in a text file. If i have a text file filled with words only, random words, not sentences, how do i find a string inside it. lets say I take a user

Solution 1:

You mean, how to find a word in this file? That's

withopen("sample.txt") asinput:
    dictionary = set(input.read().split())

then

w in dictionary

for your word w.

Solution 2:

You asked three related but different questions:

1. "how do i find a string or a list in a text file."

text = input('enter: ')
data = open("sample.txt").read()
position = data.find(text)
if position != -1:
    print("Found at position", position)
else:
    print("Not found")

2. "how do I test or check if the string input by the user exist in the text file"

text = input('enter: ')
data = open("sample.txt").read()
if text in data:
    print("Found")
else:
    print("Not found")

3. "I want to make a simple spellchecker. so from the user input string i want to check if that string matches the strings/list in the txt file"

Make a dictionary like this, globally in a module:

dictionary = open("sample.txt").read().split()

Then you use the dictionary by importing it:

from themodule import dictionary

And you check if a word is in the dictionary like so:

'word'in dictionary

Post a Comment for "How To Find A String In A Txt File"