[英]How to insert text into a text file on a specific line or after a specific word?
我需要創建一個方法,將傳遞給它的值插入到 index.html 文件的正文中,緊跟在第一個<body>
之后。
我有代碼:
class New_class
def status(sourse, hp, sleep)
@sourse = sourse
File.open(@sourse, 'a'){ |file| file.puts hp, sleep }
end
end
tamgem = New_class.new
tamgem.status("index.html", 20, 20)
如何確保傳遞給此方法的數字插入到 HTML 文檔的正文中? 另外,請注意,這只是 Ruby,不是 Rails。
您可以制作這樣的方法:
def write_after_body(original_file, new_file, *new_content)
File.open(new_file, 'w') do |file|
IO.foreach(original_file) do |line|
file.write(line)
if line.include? '<body>'
file.write(*new_content)
end
end
end
end
它將保持原始文件不變,並使用您想要的更改創建一個新文件,因為同時讀取和寫入同一個文件並不是一個好主意。 像這樣調用方法:
write_after_body("index.html", "new_index.html", 20," ", 20)
將原始文件index.html
中的所有內容復制到新文件new_index.html
中,並在<body>
標記后的新行中添加20
、 " "
和20
。 之后,如果您對結果感到滿意,您可以刪除/移動舊文件並重命名新文件。
用正則表達式或任何其他原始方法(如 StringScanner)解析 HTML很少是一個好主意。 而是使用實際理解 HTML 的 HTML 解析器 ( nokogiri )。
require 'nokogiri'
@doc = Nokogiri::HTML('<html><body></body></html>')
@doc.at('body').add_child('<h1>Hello World</h1>')
@doc.to_html
# => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><h1>Hello World</h1></body></html>\n"
Ruby 有一個內置的 class 稱為StringScanner
,它可以作為一種方便的方法來查找字符串中某些模式的 position。
為什么這對您的情況有用? 您可以嘗試查找<body>
標簽后的第一個字符的索引。
知道該索引后,您可以輕松地將 substring 插入 HTML 的正確位置。
這是一個例子:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph</p>
</body>
</html>
# Ruby script in the same folder as `index.html`.
# Library where StringScanner is located.
require 'strscan'
# Read all content of `index.html` and store it into a variable.
html = File.read('index.html')
# Create the StringScanner instance.
scanner = StringScanner.new(html)
# Then you are scanning your HTML string until the first occurence of the <body> tag.
scanner.scan_until(/<body>/)
# If your search is successful,
# then the scan pointer position will be just beyond the last character of the match.
#
# In other words,
# the scan pointer position will be the index of the first character after `<body>` tag.
index = scanner.pos
# Simple insert
updated_html = html.insert(index, "\nHello")
# Write updated content to `index.html`.
File.write('index.html', updated_html)
因此,您的 class 可能如下所示:
require 'strscan'
class New_class
def status(source, hp, sleep)
html = File.read(source)
scanner = StringScanner.new(html)
scanner.scan_until(/<body>/)
index = scanner.pos
updated_html = html.insert(index, "#{hp} #{sleep}")
File.write(source, updated_html)
end
end
tamgem = New_class.new
tamgem.status("index.html", 20, 20)
最后一點:如果您沒有任何特殊要求,請使用 CamelCase 作為 class 名稱,因為大多數 Ruby 樣式指南都建議使用 CamelCase。 以下是一些示例: Rubocop 、 Airbnb 。
資料來源:
看完這篇文章
我同意,一般來說,使用正則表達式來解析 HTML 並不是一個好主意,所以當問題相對簡單的時候你可以使用上面描述的方法,但是如果你需要更全面的東西,請參考@max answer 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.