WeixiangYan/CodeTransOcean huggingface dataset:
Task: Mad Libs


C++: #include <iostream>
#include <string>
using namespace std;

int main()
{
  string story, input;

  
  while(true)
  {
    
    getline(cin, input);

    
    if(input == "\r")
      break;

    
    story += input;
  }

  
  int begin;
  while((begin = story.find("<")) != string::npos)
  {
    
    int end = story.find(">");
    string cat = story.substr(begin + 1, end - begin - 1);

    
    cout << "Give me a " << cat << ": ";
    cin >> input;

    
    
    while((begin = story.find("<" + cat + ">")) != string::npos)
    {
      
      story.replace(begin, cat.length()+2, input);
    }
  }

  
  cout << endl << story;

  return 0;
}



Go: package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          
    m := map[string]string{} 
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}
Task: Mad Libs


C++: #include <iostream>
#include <string>
using namespace std;

int main()
{
  string story, input;

  
  while(true)
  {
    
    getline(cin, input);

    
    if(input == "\r")
      break;

    
    story += input;
  }

  
  int begin;
  while((begin = story.find("<")) != string::npos)
  {
    
    int end = story.find(">");
    string cat = story.substr(begin + 1, end - begin - 1);

    
    cout << "Give me a " << cat << ": ";
    cin >> input;

    
    
    while((begin = story.find("<" + cat + ">")) != string::npos)
    {
      
      story.replace(begin, cat.length()+2, input);
    }
  }

  
  cout << endl << story;

  return 0;
}




Java: import java.util.*;

public class MadLibs {
    
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        
        String name, gender, noun;
        
        System.out.print("Enter a name: ");
        name = input.next();
        
        System.out.print("He or she: ");
        gender = input.next();
        
        System.out.print("Enter a noun: ");
        noun = input.next();
        
        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
        
    
    }
}
Task: Mad Libs



C#: using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs = 
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, 
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, 
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}





Python: import re





template = 

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)
Task: Mad Libs




Go: package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          
    m := map[string]string{} 
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}


Java: import java.util.*;

public class MadLibs {
    
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        
        String name, gender, noun;
        
        System.out.print("Enter a name: ");
        name = input.next();
        
        System.out.print("He or she: ");
        gender = input.next();
        
        System.out.print("Enter a noun: ");
        noun = input.next();
        
        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
        
    
    }
}
Task: Mad Libs





Java: import java.util.*;

public class MadLibs {
    
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        
        String name, gender, noun;
        
        System.out.print("Enter a name: ");
        name = input.next();
        
        System.out.print("He or she: ");
        gender = input.next();
        
        System.out.print("Enter a noun: ");
        noun = input.next();
        
        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
        
    
    }
}



Python: import re





template = 

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)
Task: Mad Libs





Java: import java.util.*;

public class MadLibs {
    
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        
        String name, gender, noun;
        
        System.out.print("Enter a name: ");
        name = input.next();
        
        System.out.print("He or she: ");
        gender = input.next();
        
        System.out.print("Enter a noun: ");
        noun = input.next();
        
        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
        
    
    }
}




VB: Function mad_libs(s)
    Do
        If InStr(1,s,"<") <> 0 Then
            start_position = InStr(1,s,"<") + 1
            end_position = InStr(1,s,">")
            parse_string = Mid(s,start_position,end_position-start_position)
            WScript.StdOut.Write parse_string & "? "
            input_string = WScript.StdIn.ReadLine
            s = Replace(s,"<" & parse_string & ">",input_string)
        Else
            Exit Do
        End If
    Loop
    mad_libs = s
End Function

WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine
Task: Mad Libs




Go: package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          
    m := map[string]string{} 
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}




Python: import re





template = 

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)
Task: Mad Libs




Go: package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          
    m := map[string]string{} 
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}





VB: Function mad_libs(s)
    Do
        If InStr(1,s,"<") <> 0 Then
            start_position = InStr(1,s,"<") + 1
            end_position = InStr(1,s,">")
            parse_string = Mid(s,start_position,end_position-start_position)
            WScript.StdOut.Write parse_string & "? "
            input_string = WScript.StdIn.ReadLine
            s = Replace(s,"<" & parse_string & ">",input_string)
        Else
            Exit Do
        End If
    Loop
    mad_libs = s
End Function

WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine
Task: Mad Libs







Python: import re





template = 

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)


VB: Function mad_libs(s)
    Do
        If InStr(1,s,"<") <> 0 Then
            start_position = InStr(1,s,"<") + 1
            end_position = InStr(1,s,">")
            parse_string = Mid(s,start_position,end_position-start_position)
            WScript.StdOut.Write parse_string & "? "
            input_string = WScript.StdIn.ReadLine
            s = Replace(s,"<" & parse_string & ">",input_string)
        Else
            Exit Do
        End If
    Loop
    mad_libs = s
End Function

WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine
Task: Mad Libs


C++: #include <iostream>
#include <string>
using namespace std;

int main()
{
  string story, input;

  
  while(true)
  {
    
    getline(cin, input);

    
    if(input == "\r")
      break;

    
    story += input;
  }

  
  int begin;
  while((begin = story.find("<")) != string::npos)
  {
    
    int end = story.find(">");
    string cat = story.substr(begin + 1, end - begin - 1);

    
    cout << "Give me a " << cat << ": ";
    cin >> input;

    
    
    while((begin = story.find("<" + cat + ">")) != string::npos)
    {
      
      story.replace(begin, cat.length()+2, input);
    }
  }

  
  cout << endl << story;

  return 0;
}






Python: import re





template = 

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)
Task: Mad Libs


C++: #include <iostream>
#include <string>
using namespace std;

int main()
{
  string story, input;

  
  while(true)
  {
    
    getline(cin, input);

    
    if(input == "\r")
      break;

    
    story += input;
  }

  
  int begin;
  while((begin = story.find("<")) != string::npos)
  {
    
    int end = story.find(">");
    string cat = story.substr(begin + 1, end - begin - 1);

    
    cout << "Give me a " << cat << ": ";
    cin >> input;

    
    
    while((begin = story.find("<" + cat + ">")) != string::npos)
    {
      
      story.replace(begin, cat.length()+2, input);
    }
  }

  
  cout << endl << story;

  return 0;
}







VB: Function mad_libs(s)
    Do
        If InStr(1,s,"<") <> 0 Then
            start_position = InStr(1,s,"<") + 1
            end_position = InStr(1,s,">")
            parse_string = Mid(s,start_position,end_position-start_position)
            WScript.StdOut.Write parse_string & "? "
            input_string = WScript.StdIn.ReadLine
            s = Replace(s,"<" & parse_string & ">",input_string)
        Else
            Exit Do
        End If
    Loop
    mad_libs = s
End Function

WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine
Task: Mad Libs



C#: using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs = 
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, 
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, 
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}



Java: import java.util.*;

public class MadLibs {
    
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        
        String name, gender, noun;
        
        System.out.print("Enter a name: ");
        name = input.next();
        
        System.out.print("He or she: ");
        gender = input.next();
        
        System.out.print("Enter a noun: ");
        noun = input.next();
        
        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
        
    
    }
}
Task: Mad Libs



C#: using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs = 
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, 
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, 
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}






VB: Function mad_libs(s)
    Do
        If InStr(1,s,"<") <> 0 Then
            start_position = InStr(1,s,"<") + 1
            end_position = InStr(1,s,">")
            parse_string = Mid(s,start_position,end_position-start_position)
            WScript.StdOut.Write parse_string & "? "
            input_string = WScript.StdIn.ReadLine
            s = Replace(s,"<" & parse_string & ">",input_string)
        Else
            Exit Do
        End If
    Loop
    mad_libs = s
End Function

WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine