Python 如何查找文本文件中是否包含整个单词?

Python 如何查找文本文件中是否包含整个单词?,python,python-3.4,Python,Python 3.4,我的代码如下所示: 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:

我的代码如下所示:

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.')
代码基本上要求用户输入一个名称,如果该名称存在于文本文件中,则代码表示该名称存在,但如果不存在,则表示找不到该名称


我唯一的问题是,如果你输入部分名字,它会告诉你整个名字存在。例如,我的文本文件中的名称是:Anya、Albert和Clemont,它们在不同的行上分开。如果在提示用户输入时输入'a',代码仍然会显示名称存在,并且只会要求输入另一个名称。我理解它为什么这么做,因为“a”从技术上讲是在这条线上,但我如何使它只在它们进入整件事情时才说名称存在?我的意思是,他们输入例如‘Anya’,而不是‘a’,如果他们输入‘Anya’,代码只会说名称存在。谢谢你回答这个问题,做同样的比较。还注意到您有无限循环,这是预期的吗?当在文件中找到匹配的名称时,我更改了代码以退出该循环

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.')
输入

Anya
Albert
Clemont
输出

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!
使用函数的简短解决方案:

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.")
测试用例:

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

Enter a name: Anya
That name exists!

Enter a name: ...

代码可以简单得多,也可以短得多。使用regexp方法如果文件中有行
Ann Taylor
,那么文件中是否有名称
Ann
?如果我运行代码(在将行Ann Taylor添加到文件后),在提示时输入Ann返回名称存在。检查user\u input==line而不是user\u input in line可能会解决您的问题,因为这是示例代码,所以我无法这样做。我需要在我的另一个python文件中找到一个解决方案(由于保密原因,我无法显示),并且每一行中都有不止一个短语。例如,如果行中包含:Clemont 12345(这与我所说的其他代码类似),那么只输入Clemont将不起作用,是的,它旨在保持循环;我写的代码只有示例代码,因此我可以理解我的另一个脚本中的问题。确定:)在这种情况下,我将删除这段代码以退出while循环