Created
September 11, 2024 13:43
-
-
Save AlphaHot/556ad02f7a116a25f6be76fbd9b22366 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//go:build ignore | |
package main | |
import ( | |
"encoding/json" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
// Open the JSON file | |
file, err := os.Open("en_US.json") | |
if err != nil { | |
log.Fatalf("Error opening file: %v", err) | |
} | |
defer file.Close() | |
// Read the file content | |
data, err := ioutil.ReadAll(file) | |
if err != nil { | |
log.Fatalf("Error reading file: %v", err) | |
} | |
// Parse the JSON data into a map | |
var dictionary map[string]string | |
err = json.Unmarshal(data, &dictionary) | |
if err != nil { | |
log.Fatalf("Error parsing JSON: %v", err) | |
} | |
// Define the -m flag for the message input | |
messagePtr := flag.String("m", "", "Message to process") | |
flag.Parse() | |
// Check if the message is provided | |
if *messagePtr == "" { | |
fmt.Println("Please provide a message using the -m flag.") | |
return | |
} | |
// Read the contents of the file | |
content, err := ioutil.ReadFile(*messagePtr) | |
if err != nil { | |
message := *messagePtr | |
replacedMessage := replaceWords(message, dictionary) | |
fmt.Println(message) | |
fmt.Println(replacedMessage) | |
return | |
} | |
contentStr := string(content) | |
fmt.Println(contentStr) | |
replacedMessage := replaceWords(contentStr, dictionary) | |
fmt.Println(replacedMessage) | |
} | |
func replaceWords(message string, dictionary map[string]string) string { | |
// Use a strings.Builder for efficient string concatenation | |
var builder strings.Builder | |
// Split the message into words | |
words := strings.Fields(message) | |
for i, word := range words { | |
// Remove punctuation from the word for dictionary lookup | |
cleanedWord := strings.Trim(word, ".,!?:'\"") | |
cleanedWord = strings.ToLower(cleanedWord) | |
// Check if the cleaned word exists in the dictionary | |
if replacement, found := dictionary[cleanedWord]; found { | |
if strings.Index(replacement, ",") != -1 { | |
replacement = strings.ReplaceAll(replacement, ",", " |") | |
replacement = fmt.Sprintf("(%s)", replacement) | |
} | |
// Append the replacement word to the builder | |
builder.WriteString(replacement) | |
} else { | |
// If not found, append the original word | |
builder.WriteString(word) | |
} | |
// Append a space after each word (except the last one) | |
if i < len(words)-1 { | |
builder.WriteString(" ") | |
} | |
} | |
// Return the final string | |
return builder.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment