gpt4 book ai didi

go - 如何在Go中逐行处理文件?

转载 作者:行者123 更新时间:2023-12-01 22:33:11 25 4
gpt4 key购买 nike

在这里,我试图编写一个函数FindMajorDifference(words),该函数从文件“words.txt”返回10、11和12字符串的单词。 k字符串是字符串B,其中任何一对不同的字母之间的距离(在字母的圆形排列内)大于k。例如,

  • “silk”是1串
  • “oaks”是3字符串,2字符串和1字符串。

  • 在下面的代码中,我尝试将所有10、11和12字符串放入数组中,但是我认为这有问题。我一直在尝试找出是否正确地逐行处理了文件。
    package main

    import (
    "fmt"
    "io/ioutil"
    )

    func findMajorDifference(words []byte) []string
    {
    alpha := "abcdefghijklmnopqrstuvwxyz"
    major := []string{}

    B := string(words)

    distance := 0 // current distance between 2 distinct letters (pos1 - pos2)
    min := 26 // smallest distance between 2 distinct letters
    pos1 := 0 // position of first letter in the alpha array
    pos2 := 0 // position of second letter in the alpha array

    for i := 0; i < len(B); i++ {
    current := B[i] // current letter
    for x := 1; x < len(B); x++ {
    next := B[x] // next distinct letter
    if current != next {
    // find position of letters
    for j := 0; j < len(alpha); j++ {
    if current == alpha[j] {
    pos1 = j
    }
    }
    for k := 0; k < len(alpha); k++ {
    if next == alpha[k] {
    pos2 = k
    }
    }
    // find distance
    if pos1 > pos2 {
    distance = pos1 - pos2
    } else {
    distance = pos2 - pos1
    }
    if distance < min {
    min = distance
    }
    }
    }
    if min == 11 || min == 12 || min == 13 {
    major = append(major, string(B[i]))
    }
    }
    return major
    } // end of findMajorBinjai

    func main()
    {
    words, err := ioutil.ReadFile("words.txt")

    if err != nil {
    fmt.Println("File reading error", err)
    return
    }

    fmt.Println("test") // This line is printed
    fmt.Println("%s", findMajorDifference(words)) // Gives no output

    }

    我的代码没有给出任何错误,但是也没有输出我想要的输出。

    最佳答案

    根据您的解释,文件中有多个单词。在当前代码段中完成的方式是,文件的完整内容作为bite数组传递。如果文件中只有一个单词,这会很好地工作。如果存在多个单词,则在计算距离时还会考虑不同单词的字母。由于返回空白片,因此没有任何输出。

    您可以通过逐个阅读每个单词并将其传递给函数来克服此问题。我已经修改了您的主体,以实现预期的结果而无需更改功能

    func main() {
    // words, err := ioutil.ReadFile("words.txt")
    filehandle, err := os.Open("words.txt")
    if err != nil {
    panic(err)
    }
    defer filehandle.Close()
    scanner := bufio.NewScanner(filehandle)
    for scanner.Scan() {
    words := scanner.Text()
    fmt.Println("%s", findMajorDifference([]byte(words))) // Gives no output
    }

    }

    关于go - 如何在Go中逐行处理文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464227/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com