Ruby 逐字搜索文本
我想在txt文件中搜索特定的单词。如果我找到那个单词,我想在文件中检索紧跟其后的单词。如果我的文本文件包含:Ruby 逐字搜索文本,ruby,Ruby,我想在txt文件中搜索特定的单词。如果我找到那个单词,我想在文件中检索紧跟其后的单词。如果我的文本文件包含: "My name is Jay and I want to go to the store" 我将搜索单词want,并将该单词添加到我的数组中。我将浏览一个非常大的文本文件,因此任何关于性能的注释都将非常好。最直观的阅读方式可能如下所示: a = [] str = "My name is Jack and I want to go to the store" str.scan(/\w+
"My name is Jay and I want to go to the store"
我将搜索单词want,并将该单词添加到我的数组中。我将浏览一个非常大的文本文件,因此任何关于性能的注释都将非常好。最直观的阅读方式可能如下所示:
a = []
str = "My name is Jack and I want to go to the store"
str.scan(/\w+/).each_cons(2) {|x, y| a << y if x == 'to'}
a
#=> ["go", "the"]
要将文件读入字符串,请使用file.read。这可能不是最快的方法,但应遵循以下原则:
filename = "/path/to/filename"
target_word = "weasel"
next_word = ""
File.open(filename).each_line do |line|
line.split.each_with_index do |word, index|
if word == target_word
next_word = line.split[index + 1]
end
end
end
给定存储在文件中的文件、字符串或StringIO: 请注意,这个答案将找到每个文件最多一个匹配的速度,行操作将节省内存。如果您想在每个文件中查找多个匹配项,或者跨换行符查找匹配项,那么这可能是最好的方法。YMMV.这是一种方式: 代码 范例 较短,但效率较低,并且在处理大型文件时存在问题:
File.read(FName)[/(?<=\b#{word}\b)\W+(\w+)/,1]
假设您的文件以字符串形式加载,这是我能想到的最快速度:
word = 'want'
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
这将查找跟在您特定单词后面的所有单词。例如:
word = 'want'
string = 'My name is Jay and I want to go and I want a candy'
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
p array #=> ["to", "a"]
在我的机器上进行测试,我将这个字符串复制了500000次,执行时间达到了0.6秒。我也尝试过其他方法,如拆分字符串等,但这是最快的解决方案:
require 'benchmark'
Benchmark.bm do |bm|
bm.report do
word = 'want'
string = 'My name is Jay and I want to go and I want a candy' * 500_000
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
end
end
你可以用grep来做这件事,这会非常有用easier@meagar-那么grep会比ruby更容易在ruby数组中输入以下单词吗?@pguardiario不要迟钝。我建议将其作为Ruby的替代品。我们不知道他真正的问题是什么,因为他没有告诉我们。你是否需要在换行符之间找到匹配项,就像你想在一行的末尾一样?这会有很大的不同。@Max不需要那么精确。如果它错过了跨线休息的比赛,那也没关系。事实上,我没有考虑过格雷普,这可能会奏效。我想做的是从其他故事中构造句子。如果它是一个非常大的文件呢?旁白:你能重新格式化,使读者不必水平滚动来阅读你的代码吗?@Cary编辑答案不需要权限。如果你认为这有什么大不了的,就这么做。pg,我实际上从不编辑别人的话。老派,知识产权等等。听起来像是强迫症的斗争。我将不去管它,看看哪一方获胜:你可能是对的,或者我只是一个老家伙谁是他的方式设置。
word = 'want'
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
word = 'want'
string = 'My name is Jay and I want to go and I want a candy'
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
p array #=> ["to", "a"]
require 'benchmark'
Benchmark.bm do |bm|
bm.report do
word = 'want'
string = 'My name is Jay and I want to go and I want a candy' * 500_000
array = []
string.scan(/\b#{word}\b\s(\w+)/) do
array << $1
end
end
end