当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 周五乐趣:给我读一个故事

作者:精品下载站 日期:2024-12-14 07:43:30 浏览:13 分类:玩电脑

周五乐趣:给我读一个故事


[玩转系统] 周五乐趣:给我读一个故事

该函数使用 .NET System.Speech 类,该类似乎比传统 COM 替代方案更容易使用。这是您可以测试的片段。

Add-Type -AssemblyName System.speech
$voice = New-Object System.Speech.Synthesis.SpeechSynthesizer
$voice.Speak("Hello. I am $($voice.voice.Name)")

所以基本上,我所要做的就是获取博客文章的内容并将文本传递给语音对象。说起来容易做起来难,当您查看这段代码时您会发现这一点。


#Requires -version 3.0

Function Invoke-BlogReader {

[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter the blog post URL")]
[ValidateNotNullorEmpty()]
[string]$Url,
[ValidateScript({$_ -ge 1})]
[int]$Count = 5,
[switch]$ShowText,
[validateSet("Male","Female")]
[string]$Gender="Male"
)

Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"  

Try {
    Write-Verbose "Requesting $url"
    $web = Invoke-WebRequest -Uri $url -DisableKeepAlive -ErrorAction Stop 

    Write-Verbose "Selecting content"
    $content = $web.ParsedHtml.getElementsByTagName("div") |
     where {$_.classname -match'entry-content|post-content'} | 
     Select -first 1
}
Catch {
    Write-Warning "Failed to retrieve content from $url"
    #bail out
    Return
}

if ($content) {

    #define a regex to match sentences
    [regex]$rx="(\S.+?[.!?])(?=\s+|$)"  
    Write-Verbose "Parsing sentences"
    $sentences = $rx.matches($content.innertext) 

    Write-Verbose "Adding System.Speech assembly"
    Add-Type -AssemblyName System.speech

    Write-Verbose "Initializing a voice"
    $voice = New-Object System.Speech.Synthesis.SpeechSynthesizer

    $voice.SelectVoiceByHints($gender)

    Write-Verbose "Speaking"
    $voice.Speak($($web.ParsedHtml.title))
    $voice.speak("Published on $($web.ParsedHtml.lastModified)")
    Write-Verbose "Here are the first $count lines"     
    for ($i=0 ;$i -lt $count;$i++) {
      $text = $sentences[$i].Value
      if ($ShowText) {
        write-host "$text " -NoNewline
        }
      $voice.speak($text)
     }
     write-host "`n"
}
else {
  Write-Warning "No web content found"
}

#clean up
$voice.Dispose()

Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"  
} #end function

该函数使用 Invoke-WebRequest cmdlet 从指定网页检索内容,然后解析 HTML 来查找内容。

$web = Invoke-WebRequest -Uri $url -DisableKeepAlive -ErrorAction Stop 
Write-Verbose "Selecting content"
$content = $web.ParsedHtml.getElementsByTagName("div") |
where {$_.classname -match'entry-content|post-content'} | 
Select -first 1

这是最棘手的部分,因为不同的博客和网站使用不同的标签和类。有一个 getElementsbyClassName 方法,但这对我来说似乎是时好时坏,所以我选择了使用Where-Object 的较慢但一致的过程。

一旦我有了内容,我就可以简单地传递文本,但我意识到我可能不想听整个帖子。特别是对于我自己的,经常有脚本示例。这些听起来不太好听。所以我意识到我需要将内容解析成句子。正则表达式来救援。

[regex]$rx="(\S.+?[.!?])(?=\s+|$)"  
Write-Verbose "Parsing sentences"
$sentences = $rx.matches($content.innertext) 

不要让我解释正则表达式模式。我“找到”了它并且它有效。这才是最重要的。 $Sentences 是正则表达式匹配对象的数组。我需要做的就是将每个匹配的值传递给语音对象。另一个好处是我可以包含一个参数来显示正在读取的文本。

  for ($i=0 ;$i -lt $count;$i++) {
      $text = $sentences[$i].Value
      if ($ShowText) {
        write-host "$text " -NoNewline
        }
      $voice.speak($text)
     }

这里的所有都是它的!如果您想尝试所有选项,这里有一个示例命令:

$paramHash = @{
 Url = "http://blogs.msdn.com/b/powershell/archive/2014/08/27/powershell-summit-europe-2014.aspx"
 Count = 5
 Gender = "Female"
 ShowText = $True
 Verbose = $True
}

Invoke-BlogReader @paramHash

真正有趣的地方是使用另一个函数(我不确定我是否曾在这里发布过该函数)从 RSS 提要中获取项目。

#requires -version 3.0

Function Get-RSSFeed {

Param (
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullOrEmpty()]
[ValidatePattern("^http")]
[Alias('url')]
[string[]]$Path="http://feeds.feedburner.com/JeffsScriptingBlogAndMore"
)

Begin {
    Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"  
} #begin

Process {
    foreach ($item in $path) {
        $data = Invoke-RestMethod -Uri $item
        foreach ($entry in $data) {
            #create a custom object
            [pscustomobject][ordered]@{
                Title = $entry.title
                Published = $entry.pubDate -as [datetime]
                Link = $entry.origLink

            } #hash

        } #foreach entry
    } #foreach item

} #process

End {
    Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #end

} #end Get-RSSFeed

将所有这些放在一起,您可以获得提要,将其通过管道传输到 Out-Gridview,选择一个并让博客读给您听!

get-rssfeed | out-gridview -OutputMode Single | foreach { Invoke-BlogReader $_.link -Count 5}  

所以现在您可以拥有您的博客并收听!可能有多种方法可以增强这一点。或者您可能想将其中一些概念和技术转向另一个方向。如果是这样,我希望你能让我知道你的结局。周末愉快。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯