微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Pharo 8 的 linux 终端下标准输入 > Pharo 程序 > 标准输出?

如何解决如何在 Pharo 8 的 linux 终端下标准输入 > Pharo 程序 > 标准输出?

作为练习,我试图为 this 贡献一个 Pharo 8 解决方案。这是一个简单的排序字数挑战。例如,一种python解决方案是:

import sys

counts = {}
for line in sys.stdin:
    words = line.lower().split()
    for word in words:
        counts[word] = counts.get(word,0) + 1

pairs = sorted(counts.items(),key=lambda kv: kv[1],reverse=True)
for word,count in pairs:
    print(word,count)

sys 模块允许我们从终端通过管道传输文本,而不是从脚本内部手动打开带有路径和文件名的文件

到目前为止,我能够通过从 Pharo 中加载文件来编写 Pharo 8 解决方案来应对这一挑战:

Object subclass: #WordCounter
    instanceVariableNames: 'contents sortedResults'
    classVariableNames: ''
    package: 'MyWordCounter'

WordCounter>>readFile: aPath
    "Takes a filepath and reads the contents of the file"
    
    | stream |      
    contents := OrderedCollection new.
    stream := aPath asFileReference readStream.
    [ stream atEnd ] whileFalse: [ contents add: stream nextLine asLowercase substrings ].
    stream close.

WordCounter>>rank
    "Counts the words and sorts the results"    
            
    | dict |
    dict := Dictionary new.
    contents do:
        [ :line | line do: 
            [ :word | dict at: word put: (dict at: word ifAbsent: 0) + 1 ] ].
    sortedResults := dict associations asSortedCollection: [ :a1 :a2 | a1 value > a2 value ]

WordCounter>>show
    "Print the sorted results to transcript"
    Transcript clear.
    sortedResults do: [ :each | Transcript show: each key; show: ' '; show: each value; cr ]

定义了这个类,现在我可以通过在操场上执行以下代码来获得结果:

| obj |
obj := WordCounter new.
obj readFile: '/home/user/WordCounterPharo/kjvbible_x10.txt'.
obj rank; show.

我认为我的算法工作正常,如下所示:

enter image description here

现在的问题是,我想修改这个程序,这样,它就不再使用文件路径读取数据并将结果写入成绩单,而是从管道中提取数据并将结果打印回终端,在 Linux 中。我知道 Pharo 具有命令行功能,作为我下载 Pharo 时在终端中运行的第一个示例之一:

./pharo Pharo.image eval "42 factorial"

所以我想要的最终结果是这样的模拟输出

user@PC:~$ ./pharo Pharo.image WordCounter < kjvbible_x10.txt
user@PC:~$ the 640150
user@PC:~$ and 513130
user@PC:~$ of 346340
user@PC:~$ to 135670
user@PC:~$ that 127840
user@PC:~$ in 125030
user@PC:~$ he 102610
user@PC:~$ shall 98380
user@PC:~$ unto 89870
user@PC:~$ for 88100
user@PC:~$ i 87080
user@PC:~$ his 84500
user@PC:~$ a 81760
user@PC:~$ they 72970
user@PC:~$ be 68540
...

但我仍然不知道如何自己做。我试图遵循@tukan 的 answer,但我怀疑使用的类 OSProcess 从那时起已被删除,因为 Pharo 8 无法识别它(在操场上显示为红色,检查时返回未知变量错误)。我还注意到在 Windows 下有一个关于 pharo 的 similar question,但没有得到答复。

额外问题:在写这篇文章时,我注意到在这里共享代码,我不得不逐个方法地复制和传递代码。如果它是一个大类,那可能会有点麻烦(幸运的是,我的只有 3 个方法)。有没有更简单的方法可以一次性完成?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。