Python: 如何在 .txt 文件中搜索整个单词?

Python: How can i search for a whole word in a .txt file?

我一直在寻找解决我的问题的方法: 当用户键入已保存在 .txt 文件中的名称时,它应该打印 "true"。 如果用户名不存在,则应添加用户输入的名称。 问题是,当输入的名称是 "Julia",但 "Julian" 已经在列表中时,它甚至打印出 true。我希望你明白我的意思。 我已经在 Whosebug 上阅读了 maaany 解决方案,但在使用 .txt 文件时对我没有任何帮助 我的代码:

import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(paste) != -1:
        print("true")
    else:
        names_file.write("\n" + username)
        print(username + " got added to the list")



names_file.close()
username = input("username: ")
found = False
with open("names_file.txt", "r") as file:
    for line in file:
        if line.rstrip() == username:
            print("true")
            found = True
            break
if not found:
    with open("names_file.txt", "a") as file:
        file.write( username + "\n")
        print(username + " got added to the list")

试试这个我已经更新了我的答案。

import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
    mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    for f in file:
        f = f.strip()
        if f == paste:
            print("true")
            status = True
    if status == False:
        names_file.write("\n" + username)
        print(username + " got added to the list")



names_file.close()

你可以在名字后面加上换行符,搜索带有换行符的名字:

import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes('\n' + username + '\n', 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
    mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(paste) != -1:
        print("true")
    else:
        names_file.write('\n' + username + '\n')
        print(username + " got added to the list")

names_file.close()

这不适用于内部有空格的名称 -- 对于这种情况,您必须定义不同的分隔符(如果所有名称都以大写字母开头,并且名称中间没有大写字母,那么你可以在名字前省去换行符)