squ*_*shy 5 string parsing r extract
我需要从文件之间结构不同的文本文件中提取信息。虽然这可以使用宏来完成,但由于文件是可变的,请按行号进行选择。并且行内间距并非对所有文件都成功。
我想知道是否有人可以告诉我是否有一种方法可以解析txt文件并按关键字搜索并提取关键字后的信息?例如,像流量:99.99,我想提取 99.99。另一个问题是,使用流量示例时,流量会在每个文件中出现多次。有没有办法别名/索引 Flow Rate: 以便我可以在第三次出现时进行选择?
欢迎任何提示或技巧。我知道如何在识别关键字时打印整行,但不知道如何处理多次出现,并且只选择关键字后面的数字:
all_data = readLines("Unit 5 2013.txt")
hours_of_operation <- grep("Annual Hours of Operation: ",all_data)
all_data[hours_of_operation]
[1] " Annual Hours of Operation: 8760.0 hours/yr"
Run Code Online (Sandbox Code Playgroud)
谢谢
J
以下内容可能会有所帮助。我假设您将文本转换为字符向量
数据示例
注意:如果“Flow Rate”为大写,您可能需要先使用tolower(ex)
ex<-c("The annual observed flow rate: 99.99")
Run Code Online (Sandbox Code Playgroud)
正则表达式和正则匹配
这里 regexpr 搜索句号前后各有两位数字的数字。
res<-regmatches(ex, regexpr("[0-9]{1,2}.[0-9]{1,2}",ex))
Run Code Online (Sandbox Code Playgroud)
使用位置参数
另一种方法是使用 cwhmisc 库。该解决方案搜索单词“rate”的起始位置。预计 5 个位置之后就是您需要的数字,然后您可以对该数字进行子串。
library(cwhmisc)
A<-cpos(ex,"rate", start=1) #position in string
res<-substr(ex, start=A+5, stop=A+9)
Run Code Online (Sandbox Code Playgroud)
如果多次出现流量
将向量的元素拆分为子字符串并像以前一样捕获数字。
ex<-c("The annual observed flow rate: 99.99; the monthly flow rate: 90.03; the weekly observed flow rate: 92.22")
ndat<-unlist(strsplit(ex, "flow"))
Run Code Online (Sandbox Code Playgroud)