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

问题描述 投票:0回答:1

我一直在寻找解决我的问题的方法:当一个用户输入一个已经保存在.txt文件中的名字时,它应该打印 "true".如果用户名还不存在,它应该添加用户输入的名字。我希望你能明白我的意思,我已经在stackoverflow上阅读了很多解决方案,但当我使用一个.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()
python text-files
1个回答
1
投票

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

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()

1
投票
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")

1
投票

你可以在名字后面加上换行符,然后用换行符搜索名字。

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()

这对里面有空格的名字不起作用 -- 在这种情况下,你必须定义不同的分隔符(如果所有名字都以大写字母开头,而且名字中间没有大写字母,那么你可以在名字前不加换行符)。

© www.soinside.com 2019 - 2024. All rights reserved.