简体   繁体   中英

How do i find if a whole word is in a text file?

My code looks like this:

file = open('names.txt', 'r')
fileread = file.read()
loop = True
while loop is True:
    with open('names.txt', 'r') as f:
        user_input = input('Enter a name: ')
        for line in f:
            if user_input in line:
                print('That name exists!')
            else:
                print('Couldn\'t find the name.')

The code basically asks the user for a name, and if the name exists in the text file, then the code says it exists, but if it doesn't it says it couldnt find it.

The only problem I have is that if you even enter part of the name, it will tell you the whole name exists. For example the names in my text file are: Anya, Albert and Clemont, all seperated on different lines. If i were to enter 'a' when prompted for user_input, the code will still say the name is present, and will just ask for another name. I understand why its doing this, because 'a' is technically in the line, but how do i make it so that it only says the name exists if they enter the whole thing? By whole thing i mean they enter for example 'Anya', rather than 'a' and the code only says the name exists if they enter 'Anya'. Thanks

Short solution usingre.seach() function:

import re

with open('lines.txt', 'r') as fh:
    contents = fh.read()

loop = True
while loop:
    user_input = input('Enter a name: ').strip()
    if (re.search(r'\b'+ re.escape(user_input) + r'\b', contents, re.MULTILINE)):
        print("That name exists!")
    else:
        print("Couldn't find the name.")

Test cases:

Enter a name: Any
Couldn't find the name.

Enter a name: Anya
That name exists!

Enter a name: ...

To answer the question , just do equal comparison. Also noted that You have infinite loop , is that expected ? I changed the code to exit that loop when a matching name found in the file

file = open('inv.json', 'r')
fileread = file.read()
loop = True
while loop is True:
    with open('inv.json', 'r') as f:
        user_input = raw_input('Enter a name: ')
        for line in f:
            if user_input == line.strip():
                print('That name exists!')
                break
                #loop =False
            else:
                print('Couldn\'t find the name.')

Input

Anya
Albert
Clemont

Output

Enter a name: an
Couldn't find the name.
Couldn't find the name.
Couldn't find the name.

Enter a name: An
Couldn't find the name.
Couldn't find the name.
Couldn't find the name.

Enter a name: Any
Couldn't find the name.
Couldn't find the name.
Couldn't find the name.

Enter a name: Anya
That name exists!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM