Skip to content

Instantly share code, notes, and snippets.

@PrateekKumarSingh
Created January 13, 2017 15:04
Show Gist options
  • Save PrateekKumarSingh/0d202c44cd520df33dec50c6c5053d84 to your computer and use it in GitHub Desktop.
Save PrateekKumarSingh/0d202c44cd520df33dec50c6c5053d84 to your computer and use it in GitHub Desktop.
Function Get-Sentence
{
[cmdletBinding()]
[alias('gs')]
param(
[parameter(mandatory=$true)] [String]$Word,
[int] $count = 10,
[int] $WordLimit,
[Switch] $HighlightWord
)
Try
{
Write-Verbose "Sending Webrequest to http://sentence.yourdictionary.com/$Word for sentences"
$Results = Invoke-WebRequest "http://sentence.yourdictionary.com/$Word" -TimeoutSec 5 -DisableKeepAlive
$ErrorMsg = "Couldn't find any sentences with word `"$($Word.toupper())`", please try again with another word "
# Condition to check if data is returned or not
# In response to the Web request
If($Results)
{
$i=0
Write-Verbose "Harvesting data from web request"
# Filtering out sentences from the data harvested from the website
$Data = $Results.ParsedHtml.getElementsByTagName('Div')| Where{$_.ClassName -eq 'li_content'}
# Condition to check Data contains Sentences or not
If($Data)
{
Write-Verbose "Populating the output"
$Sentences = Foreach($Sentence in $Data)
{
$WordCount = $Sentence.textContent.Split(' ').count
# Filter out Sentence that not comply the word limit
If($WordLimit -and $WordCount -le $WordLimit)
{
$i=$i+1
''|Select @{n='#';e={$i}},
@{n='WordCount';e={$WordCount}},
@{n='Sentence';e={$Sentence.textContent}}
}
elseif(-not $WordLimit)
{
$i=$i+1
''|Select @{n='#';e={$i}},
@{n='WordCount';e={$WordCount}},
@{n='Sentence';e={$Sentence.textContent}}
}
}
$Sentences = $Sentences| Select -First $count
# Condition and Logic to highlight the word
# For which you're looking for sentence examples
If($HighlightWord)
{
$Sentences.sentence | ForEach-Object {
$Words = $_.split()
$Words | ForEach-Object {
If($_ -like "*$word*")
{
Write-Host "$_" -NoNewline -Fore Black -Back Yellow;
Write-Host " " -NoNewline
}
else
{
Write-Host "$_ " -NoNewline
}
}
[System.Environment]::NewLine
}
}
else
{
$Sentences
}
}
Else
{
Write-Host $ErrorMsg -ForegroundColor Red
}
}
else
{
Write-Host $ErrorMsg -ForegroundColor Red
}
}
catch
{
Write-host "ERROR: $_" -ForegroundColor Red
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment