我在R中工作(在Windows操作系统上),试图在不将文件加载到内存的情况下计算文本文件中的字数。这样做的目的是获取文件大小、行数、字数等方面的统计数据。调用R的system()函数,使用find进行行计数,并不难:如何在Windows命令提示符中执行“单词计数”命令
lineCount <- system(paste0('find /c /v "" ', path), intern = T)我试图使用的单词计数命令是一个PowerShell命令:Measure-Object。我可以在不抛出错误的情况下运行以下代码,但它返回一个不正确的计数。
print(system2("Measure-Object", args = c('count_words.txt', '-Word')))
[1] 127该文件,count_words.txt上有数百万字左右。我还用更少的单词在一个.txt文件上测试了它。
"There are seven words in this file."但是,伯爵再次返回为127。
print(system2("Measure-Object", args = c('seven_words.txt', '-Word')))
[1] 127system2()是否识别PowerShell命令?使用Measure-Object时调用函数的正确语法是什么?为什么不管实际单词数如何,它都返回相同的值?
发布于 2018-10-18 17:54:32
问题--概览
所以,这里有两个问题:
system2()使用powershell解决方案
command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
system2("powershell", args = command)将C:/Users/User/Documents/test2.txt替换为文件的任何路径。我创建了两个.txt文件,其中一个文件的文本是“这个文件中有七个单词”。另一篇文章是“但是这个文件里有八个字。”然后,我在R中运行了以下代码:
command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
system2("powershell", args = command)
Lines Words Characters Property
----- ----- ---------- --------
7
command <- "Get-Content C:/Users/User/Documents/test2.txt | Measure-Object -Word"
system2("powershell", args = command)
Lines Words Characters Property
----- ----- ---------- --------
8 更多解释
来自help("system2")
system2调用命令指定的OS命令。
一个主要问题是,Measure-Object不是一个系统命令--它是一个PowerShell命令。PowerShell的系统命令是powershell,这是您需要调用的。
此外,您还没有正确的PowerShell语法。如果您查看一下医生们,您将看到您真正想要的PowerShell命令是
Get-Content C:/Users/User/Documents/count_words.txt | Measure-Object -Word(查看链接文档中的示例3)。
https://stackoverflow.com/questions/52878730
复制相似问题