将文本文件切片后进行比较。

huangapple go评论86阅读模式
英文:

Putting text file into slice then compare

问题

我正在编写一个程序,逐行读取一个.txt文件中的用户名,并验证该用户名是否存在。然后,我创建了一个切片,并将文件转换为字符串,并将其附加到字符串切片中。现在,我想使用for循环遍历切片,查找文件中的用户名,并将其与包含用户名的另一个字符串变量进行比较。我想检查并查看它是否在切片中。最好的方法是什么?我尝试使用for循环和要检查的用户名变量的切片范围内的元素进行比较,但它不起作用。换句话说,我想找出一种最佳方法,即从上到下包含一系列用户名的txt文件,让我的程序从该文本文件中读取(循环),并将其与字符串变量中的预定项(用户名)进行比较,确定是否匹配。

用户名(字符串变量)== 文本文件中的用户名

*另外,用户名变量将基于程序用户输入的内容。因此,我最终要检查的是,当用户输入他们的用户名时,程序将验证它是否在文件中。谢谢。

我尝试过的代码示例:

var readSystemCtl []string
readSystemCtl = append(readSystemCtl, string(file))
for _, username := range readSystemCtl {
    if username == input {
        // 如果为真,则继续程序
        break
    } else {
        // 做其他事情
    }
}

注意:string(file)是我要读取的文本文件;input是用户在程序中预先确定的字符串变量,用于存储他们的用户名输入。

英文:

I am writing a program where I take usernames line by line in a .txt file and verify that the username is in it. I have then created a slice and converted the file into a string and appended it to the string slice. I'm now trying to loop over the slice using a for loop to find a username that's in the file and compare it to another string variable that contains the username. I want to check for and see if it is in the slice. What is the best way to do this? I've tried comparing the elements in range using a for loop of the slice with the variable with the username I want to check but it's not working. So in other words I want to find out the best way to take a txt file that contains a list of just usernames added to it from top to bottom, have my program read (loop over) from that text file, and compare it with a predetermined item (username) in a string variable with what's in the text file and determine if it matches or not.

Username (string variable) == Username (in text file)

*Also the username variable will be based on what a user of the program enters into it. So I'm trying to ultimately check if when a user enters their username the program will verify if it's in the file or not. Thanks.

Code example I've tried:

var readSystemCtl []string
readSystemCtl = append(readSystemCtl, string(file))
for _, username := range of readSystemCtl {
    if username == input {
        //Continue program if true 
        break
    }else {
        //Do something else
    }
}

Note: string(file) is the text file i'm trying to read from; and input, is the string variable that the user will had input for their username that is predetermined earlier in the program.

答案1

得分: 2

作为一名Go程序员,我迅速将您的整体应用需求翻译成了一个Go程序。然后我将其与您的代码进行了比较。我不明白为什么您要使用Go切片的线性搜索,而不是使用Go映射的随机访问。


在比较用户名是否相等之前,使用strings.TrimSpace去除空格,并且为了不区分大小写,将其转换为小写(strings.ToLower)。


users.go

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

func loadUsers(r io.Reader) (map[string]bool, error) {
	users := make(map[string]bool)
	scnr := bufio.NewScanner(r)
	for scnr.Scan() {
		user := strings.TrimSpace(scnr.Text())
		if len(user) > 0 {
			user = strings.ToLower(user)
			users[user] = true
		}
	}
	if err := scnr.Err(); err != nil {
		return nil, err
	}
	return users, nil
}

func loadUsersFile(name string) (map[string]bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	users, err := loadUsers(f)
	if err != nil {
		return nil, err
	}
    return users, nil
}

func isUser(users map[string]bool, user string) bool {
	user = strings.TrimSpace(user)
	user = strings.ToLower(user)
	return users[user]
}

func main() {
	users, err := loadUsersFile("users.txt")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	scnr := bufio.NewScanner(os.Stdin)
	for scnr.Scan() {
		user := scnr.Text()
		fmt.Print("User: ", user)
		if isUser(users, user) {
			fmt.Println(" found")
		} else {
			fmt.Println(" not found")
		}
	}
	if err := scnr.Err(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

$ cat users.txt
username1
Username2
UserName3
$ go build users.go
$ ./users
User Name X
User: User Name X not found
username3
User: username3 found
$
英文:

As a Go programmer, I quickly translated your overall application requirements into a Go program. I then compared it to your code. I don't understand why you use a linear search of a Go slice. Why not use a random access to a Go map?


Before comparing user names for equality, trim white space (strings.TrimSpace) and, for case insensitivity, convert to lowercase (strings.ToLower).


users.go

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

func loadUsers(r io.Reader) (map[string]bool, error) {
	users := make(map[string]bool)
	scnr := bufio.NewScanner(r)
	for scnr.Scan() {
		user := strings.TrimSpace(scnr.Text())
		if len(user) > 0 {
			user = strings.ToLower(user)
			users[user] = true
		}
	}
	if err := scnr.Err(); err != nil {
		return nil, err
	}
	return users, nil
}

func loadUsersFile(name string) (map[string]bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	users, err := loadUsers(f)
	if err != nil {
		return nil, err
	}
    return users, nil
}

func isUser(users map[string]bool, user string) bool {
	user = strings.TrimSpace(user)
	user = strings.ToLower(user)
	return users[user]
}

func main() {
	users, err := loadUsersFile("users.txt")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	scnr := bufio.NewScanner(os.Stdin)
	for scnr.Scan() {
		user := scnr.Text()
		fmt.Print("User: ", user)
		if isUser(users, user) {
			fmt.Println(" found")
		} else {
			fmt.Println(" not found")
		}
	}
	if err := scnr.Err(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

$ cat users.txt
username1
Username2
UserName3
$ go build users.go
$ ./users
User Name X
User: User Name X not found
username3
User: username3 found
$ 

huangapple
  • 本文由 发表于 2023年3月19日 04:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75778480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定