最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Ruby - searching a file for certain words and replacing them - Stack Overflow

programmeradmin1浏览0评论

I have a list of words and a text file and I'd need to find out if any of the words on the list are found in the text file. In addition I'd need to replace those words with "DELETED" and save this file with another name.

I'm very new with Ruby and Python this all seems really hard. I kow I need to open the file and read it line by line. I konw how to check if the line includes one certain word but not if it includes one word from a list.

File.open("text.txt") do |x|
    x.each do |line|
        # WHAT TO PUT HERE?
    end
end

thank you in advance!

I have a list of words and a text file and I'd need to find out if any of the words on the list are found in the text file. In addition I'd need to replace those words with "DELETED" and save this file with another name.

I'm very new with Ruby and Python this all seems really hard. I kow I need to open the file and read it line by line. I konw how to check if the line includes one certain word but not if it includes one word from a list.

File.open("text.txt") do |x|
    x.each do |line|
        # WHAT TO PUT HERE?
    end
end

thank you in advance!

Share Improve this question edited Mar 17 at 14:14 engineersmnky 29.8k2 gold badges41 silver badges63 bronze badges asked Mar 17 at 12:28 Tessan88Tessan88 111 bronze badge 1
  • To see if a line contains a word in a list, go through the list and "check if the line includes [that] one certain word". – Scott Hunter Commented Mar 17 at 12:31
Add a comment  | 

1 Answer 1

Reset to default 1

I would do something like this:

BLOCK_PATTERN = Regexp.union(["word_1", "word_2", "..."])  
INPUT_FILE    = "input.txt"  
OUTPUT_FILE   = "output.txt"  

File.open(OUTPUT_FILE, "w") do |output_file|  
  File.foreach(INPUT_FILE) do |line|  
    output_file << line.gsub(BLOCK_PATTERN, "DELETED")  
  end  
end
发布评论

评论列表(0)

  1. 暂无评论