繁体   English   中英

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

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

我的代码如下所示:

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”在技术上是行中的,但是我该如何制作才能使其仅在他们输入整个内容时才表示该名称存在? 总的来说,我的意思是他们输入例如“Anya”,而不是“a”,如果他们输入“Anya”,代码只会说名称存在。 谢谢

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

要回答这个问题,只需进行相等比较。 还注意到你有无限循环,这是预期的吗? 当在文件中找到匹配的名称时,我更改了代码以退出该循环

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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