在文本文件中搜索单词并显示(Ruby) [英] Search for word in text file and display (Ruby)

查看:66
本文介绍了在文本文件中搜索单词并显示(Ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从用户那里获取输入,搜索文本文件(不区分大小写),然后如果匹配(使用文件中单词的大小写)则显示文件中的匹配项.我不知道如何从文件中获取单词,这是我的代码:

I'm trying to take input from the user, search through a text file (case insensitively), and then display the match from the file if it matches (with the case of the word in the file). I don't know how to get the word from the file, here's my code:

found = 0
words = [] 

puts "Please enter a word to add to text file"
input = gets.chomp

#Open text file in read mode 
File.open("filename", "r+") do |f|

  f.each do |line|
    if line.match(/\b#{input}\b/i)
      puts "#{input} was found in the file."   # <--- I want to show the matched word here
      #Set to 1 indicating word was found
      found = 1
    end
  end
end 

推荐答案

所以,你要做的就是将 match 方法的结果存储起来,然后就可以得到实际匹配的单词了其中,即.

So, what you want to do is to store the result of the match method, you can then get the actual matched word out of that, ie.

if m = line.match( /\b#{input}\b/i )
  puts "#{m[0]} was found in the file."
  # ... etc.
end

更新

顺便说一句,你没有问 - 但在这种情况下我会使用 scan,这样我就会在每一行上得到一个匹配单词的数组(当有多个匹配时同一行),类似这样:

Update

Btw, you didn't ask - but I would use scan in this case, so that I got an array of the matched words on each line (for when there's more than one match on the same line), something like this:

if m = line.scan( /\b#{input}\b/i )
  puts "Matches found on line #{f.lineno}: #{m.join(', ')}"
  # ... etc.
end

这篇关于在文本文件中搜索单词并显示(Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆