简体   繁体   English

如何从文本文件中获取匹配项并将其输出到数组中?

[英]How do I get matches from a text file and output them in an array?

I'm using a text file with lines of movies. 我正在使用带有电影行的文本文件。 If a user inputs Oz , I want to output all the movies in the file that have the word Oz in it. 如果用户输入Oz ,我想输出文件中包含单词Oz所有电影。

This is what I have so far. 到目前为止,这就是我所拥有的。

puts "Enter the keyword you want to search for: "
keyword = gets
movies_file = File.new("movies.txt", "r")
movies = movies_file.read
movies_list = movies.split(" ")
match_list = []
movies_list.each do |w|
  matchObj = w.match(keyword)
  if matchObj then
    matchlist.push(matchObj.captures[0])
  end
end
match_list.each do |title|
  puts title
end

Presuming you've got the file organized like this: 假设您已将文件整理成这样:

Wizard of Oz
Battlefield Earth
Twilight
Ozymandias

Then you can read it in this way: 然后,您可以通过以下方式阅读它:

lines = File.readlines('movies.txt').map(&:chomp)

Then to find matching lines: 然后找到匹配的行:

matches = lines.grep(phrase)

There's no need for all the each stuff. 没有必要对所有的each东西。 Also the then on an if is almost never put in there, it's just useless decoration. 而且, if几乎没有, then就放在if上,那只是无用的装饰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数组创建的字符串中获取文本输出,以使其不被缩短? - How do I get a text output from a string created from an array to remain unshortened? 如何从文件中读取行并将其存储到数组中 - How do I read lines from a file and store them into an array 如何初始化文本并将其从文件传递到类数组以在C ++中输出? - How do I initialize and pass an text from a file to a class array for output in c++? 如何从该对象数组获得以下输出? - How do I get the following output from this array of objects? C#:带有4个字母单词的文本文件,用制表符分隔-如何将它们转换为数组? - C#: Text file with 4 letter words, separated with tabs - how do I convert them to an array? 如何使用正则表达式查找特定匹配项并将其放入字符串数组? - How do I find specific matches using regex and put them in a string array? 如何获得此阵列的正确输出? - How do I get the right output for this array? 从preg_replace获取匹配项并将其用作数组键 - Get matches from a preg_replace and use them as an array key 我如何在json文件中获取每个json元素并将它们放入数组中 - How do i get every json elemet in a json file and put them in an array 如何从文本文件中读取Java中的二维数组 - How do I read from a text file into a 2 dimensional array in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM