如何找到整个单词是否在文本文件中?

时间:2017-02-03 18:23:27

标签: 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:
                print('That name exists!')
            else:
                print('Couldn\'t find the name.')

代码基本上要求用户输入一个名称,如果该名称存在于文本文件中,那么代码表明它存在,但如果它没有说它无法找到它。

我唯一的问题是,如果你甚至输入名称的一部分,它会告诉你整个名字存在。例如,我的文本文件中的名称是:Anya,Albert和Clemont,它们都分隔在不同的行上。如果我要进入'当提示输入user_input时,代码仍然会显示该名称,并且只会询问另一个名称。我明白为什么要这样做,因为' a'在技​​术上是在行,但我怎么做它只是说如果他们进入整个事情名称存在?整个事情我的意思是他们进入例如“安雅”,而不是' a'并且代码只表示如果他们输入“安雅”,该名称就存在。感谢

2 个答案:

答案 0 :(得分:2)

使用re.seach()函数的简短解决方案:

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: ...

答案 1 :(得分:0)

要回答这个问题,只需做同等比较。还注意到你有无限循环,这是预期的吗?当在文件

中找到匹配的名称时,我更改了代码以退出该循环
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!