在文本文件中搜索单词并显示(Ruby)
我试图从用户那里获取输入,搜索文本文件(不区分大小写),然后显示文件中匹配的内容(与文件中单词的大小写匹配)。我不知道如何从文件中获取单词,这是我的代码:在文本文件中搜索单词并显示(Ruby),ruby,regex,search,words,Ruby,Regex,Search,Words,我试图从用户那里获取输入,搜索文本文件(不区分大小写),然后显示文件中匹配的内容(与文件中单词的大小写匹配)。我不知道如何从文件中获取单词,这是我的代码: 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 |lin
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
found=0
单词=[]
放置“请输入要添加到文本文件的单词”
input=gets.chomp
#以读取模式打开文本文件
文件.open(“filename”,“r+”)do | f|
f、 每行|
if line.match(/\b#{input}\b/i)
将“#{input}放在文件中。”#因此,您要做的是存储match
方法的结果,然后您可以从中获取实际匹配的单词,即
if m = line.match( /\b#{input}\b/i )
puts "#{m[0]} was found in the file."
# ... etc.
end
更新
顺便说一句,你们并没有问-但在这种情况下我会使用scan
,这样我在每一行上都会得到一个匹配词的数组(当同一行上有多个匹配词时),类似这样:
if m = line.scan( /\b#{input}\b/i )
puts "Matches found on line #{f.lineno}: #{m.join(', ')}"
# ... etc.
end
如果您不需要报告匹配的位置,并且文件不太大,您可以这样做:
File.read("testfile").scan /\b#{input}\b/i
让我们试试看:
text = <<THE_END
Now is the time for all good people
to come to the aid of their local
grocers, because grocers are important
to our well-being. One more thing.
Grocers sell ice cream, and boy do I
love ice cream.
THE_END
input = "grocers"
F_NAME = "text"
File.write(F_NAME, text)
File.read(F_NAME).scan /\b#{input}\b/i
# => ["grocers", "grocers", "Grocers"]
text=您的代码实际上与您的注释不匹配。精确地运行代码,我看不到您描述的bug。文件中后续行中的一个单词被正确地报告为已找到。另外,FWIW,在对代码进行了我想象中的更改之后,我也无法重现您的第一个问题。也就是说,在删除拆分后,x的循环,并将x
替换为input
——如果一个单词在同一行上存在两次,则只打印一次。好的,但如果将x替换为行,则打印出整行,而不仅仅是一个单词。如何打印出文件中的一个单词?如我所说,将x
替换为input
。如果要以小写形式显示输入的单词,请执行input.downcase
。在puts行上用输入替换x只显示他们输入的单词,而不是文件中的单词。我希望它显示'好',如果它在文件和用户输入'好',我试图扫描文字从文本文件,这是从具体的文本开始,如“aa1”,“aa2”,“aa3”。所以“aa”对所有单词来说都很常见,我想得到所有以“aa”开头的单词,我该怎么做??