2016-08-06 10 views
0

私はテキストファイルを入力として受け取り、すべての行を読み込んで電子メールとして検証しようとする小さなスクリプトを作成しました。パスすると、その行を新しい(クリーンな)ファイルに書き出します。渡されない場合は、空白を取り除き、それを再度検証しようとします。現在、この時間が経過すると、その行を新しいファイルに書き込み、失敗した場合はその行を無視します。ファイルに書き込む前に重複を確認する方法はありますか?

私のスクリプトは、出力ファイルに重複した電子メールを書き込む可能性があります。どのように私は周りに移動し、書き込みの前に出力ファイルに存在する重複をチェックする必要がありますか?ここで

は、関連するコードです:

// create reading and writing buffers 
    scanner := bufio.NewScanner(r) 
    writer := bufio.NewWriter(w) 

    for scanner.Scan() { 
     email := scanner.Text() 

     // validate each email 
     if !correctEmail.MatchString(email) { 
      // if validation didn't pass, strip and lowercase the email and store it 
      email = strings.Replace(email, " ", "", -1) 
      // validate the email again after cleaning 
      if !correctEmail.MatchString(email) { 
       // if validation didn't pass, ignore this email 
       continue 
      } else { 
       // if validation passed, write clean email into file 
       _, err = writer.WriteString(email + "\r\n") 
       if err != nil { 
        return err 
       } 
      } 

     } else { 
      // if validation passed, write the email into file 
      _, err = writer.WriteString(email + "\r\n") 
      if err != nil { 
       return err 
      } 
     } 

    } 

    err = writer.Flush() 
    if err != nil { 
     return err 
    } 

答えて

1

あなたは、このようなセットとして内蔵されたマップ移動を使用することがあります。ここでは

package main 

import (
    "fmt" 
) 

var emailSet map[string]bool = make(map[string]bool) 

func emailExists(email string) bool { 
    _, ok := emailSet[email] 
    return ok 
} 

func addEmail(email string) { 
    emailSet[email] = true 
} 

func main() { 
    emails := []string{ 
     "[email protected]", 
     "[email protected]", 
     "[email protected]", 
     "[email protected]", // <- Duplicated! 
    } 
    for _, email := range emails { 
     if !emailExists(email) { 
      fmt.Println(email) 
      addEmail(email) 
     } 
    } 
} 

出力されます:

[email protected] 
[email protected] 
[email protected] 

あなたはThe Go Playgroundで同じコードを試してください。

+1

それは完璧です。私はあなたのソリューションを組み込むために自分のコードを編集しました。それはエレガントで教えています。ありがとう! – Arthmost

2

writerが、その後WriteString内部カスタムWriteString

を作成する実装タイプを作成し、あなたがあなたの電子メールを保存し、ファイルを開く各メールを反復して、新しいを保存電子メール。

+0

あなたの指示に基づいて指示に従うことができませんでした。マップに基づいた別のソリューションはうまくいった。 – Arthmost

関連する問題