Python:如何在.txt文件中搜索整个单词?
我一直在寻找解决我问题的方法: 当用户键入已保存在.txt文件中的名称时,应打印“true”。 如果用户名不存在,则应添加用户名,即用户键入的用户名。 问题是,当输入的名字是“Julia”时,它甚至打印为true,但“Julian”已经在列表中。我希望你明白我的意思。 我已经阅读了stackoverflow上的任何解决方案,但在使用.txt文件时没有任何解决方案 我的代码:Python:如何在.txt文件中搜索整个单词?,python,text-files,Python,Text Files,我一直在寻找解决我问题的方法: 当用户键入已保存在.txt文件中的名称时,应打印“true”。 如果用户名不存在,则应添加用户名,即用户键入的用户名。 问题是,当输入的名字是“Julia”时,它甚至打印为true,但“Julian”已经在列表中。我希望你明白我的意思。 我已经阅读了stackoverflow上的任何解决方案,但在使用.txt文件时没有任何解决方案 我的代码: 试试这个,我已经更新了我的答案 import mmap import re status = False username
试试这个,我已经更新了我的答案
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()
您可以在名称后添加换行符,并使用换行符搜索名称:
导入mmap
用户名=输入(“用户名:”)
names\u file=open(“names\u file.txt”、“a”)
粘贴=字节('\n'+用户名+'\n',utf-8')
打开(“names_file.txt”,“rb”,0)作为文件\
mmap.mmap(file.fileno(),0,access=mmap.access\u READ)为s:
如果s.查找(粘贴)!=-1:
打印(“真实”)
其他:
名称\u文件。写入('\n'+用户名+'\n')
打印(用户名+“已添加到列表”)
name_file.close()
这对内部空格的名称无效。对于这样的情况,您必须定义不同的分隔符(如果所有的名字都以大写字母开头,并且在名称中间没有大写字母,那么您可以在名称之前保留换行符)
您可以添加一个文本文件的片段吗?<代码> S.查找(粘贴)将尝试在s
中查找子字符串粘贴
。对于yeahJuliatueu
,您的代码也将返回True。如果你想搜索单词Julia,你需要在单词之间搜索。这是否回答了你的问题?
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()