簡體   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