检查文本文件中是否存在字符串 [英] Check if string exists in a text file

查看:76
本文介绍了检查文本文件中是否存在字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有:

def CheckUserExists(user):
    with open("C:/~/database.txt", 'r') as file:
        if re.search(user, file.read()):
            return True
        else:
            return False

username = input("Please enter you Username: ")
if CheckUserExists(username) == True:
    print("You exist!")
else:
    print("This user does not exist...")

但是,如果您输入例如字母 'a' 并且是一个名为 'brain' 的用户;搜索选取 a 并返回 True.如何搜索整个单词?

However if you enter for example the letter 'a' and the is a user called 'brain'; the search picks up the a and returns True. How do I search for whole words?

我看过这里:如果检查 Python字符串在文本文件中并打印该行? 但是我不明白这段代码:

I have looked here: How to check in Python if string is in a text file and print the line? however I don't understand the piece of code:

re.search("\b{0}\b".format(w),line)

推荐答案

正则表达式,\b指的是词边界处的空字符串,其中词是\w+,或[A-Za-z0-9_]+

The regular expression, \b, refers to the empty string at a word boundary, where word is \w+, or [A-Za-z0-9_]+

如果您每行有一个名称(名称周围没有其他空格),您可以使用 ^{0}$re.M 按行搜索或 re.MULTILINE 标志

If you have one name per line (with no other whitespace around the names), you can search by line with ^{0}$ with the re.M or re.MULTILINE flag

看起来像这样:

def CheckUserExists(user):
    with open("C:/~/database.txt", 'r') as file:
        if re.search('^{0}$'.format(re.escape(user)), file.read(), flags=re.M):
            return True
        else:
            return False

username = input("Please enter you Username: ")
if CheckUserExists(username): # it's redundant to check if == True here
    print("You exist!")
else:
    print("This user does not exist...")

尽管评论和答案建议,如果你这样做

Although a comment and an answer suggest, if you do

if user in file.read()

你可能有误报.

这篇关于检查文本文件中是否存在字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆