Sabbib Chow Dhury
Sabbib Chow Dhury

Reputation: 31

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 input, how do I test or check if the string input by the user exist in the text file.

so far i have this:

x = open('sample.txt')

for a in x:
    b = a.split()        #converts the string from the txt to a list

c = input('enter: ')        #user input

if any(c in a for a in b):
    print('yes')

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

Upvotes: 3

Views: 7620

Answers (2)

Lennart Regebro
Lennart Regebro

Reputation: 172367

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

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363817

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

with open("sample.txt") as input:
    dictionary = set(input.read().split())

then

w in dictionary

for your word w.

Upvotes: 5

Related Questions