我有一个 Markdown 文本文档,其中包含多个部分,并且位于该部分的主题标签下方。主题标签的格式为 #oneword#
或 #multiple Words hashtag#
。
我需要在 ruby 中提取部分及其主题标签。
示例
# Section 1
#hash1# #hash tag 2# #hashtag3#
Some text
# Section 2
#hash1# #hash tag 4# #hash tag2#
Some text too
我想要得到
{"Section 1"=>["hash1", "hash tag 2", "hashtag3"],
"Section 2"=>["hash1", "hash tag 4", "hash tag2"]}
我们可以从 grep 进入吗?
最佳答案
当遇到这样的问题时,我倾向于使用构建器模式。它有点冗长,但通常非常可读且非常灵活。
主要思想是你有一个“阅读器”,它只需查看你的输入并查找“ token ”,在本例中为行,当它找到它识别的 token 时,它会通知构建器它找到了一个 token 兴趣。构建器根据“读者”的输入构建另一个对象。 以下是“DocumentBuilder”的示例,它从“MarkdownReader”获取输入,构建您正在查找的哈希。
class MarkdownReader
attr_reader :builder
def initialize(builder)
@builder = builder
end
def parse(lines)
lines.each do |line|
case line
when /^#[^#]+$/
builder.convert_section(line)
when /^#.+\#$/
builder.convert_hashtag(line)
end
end
end
end
class DocumentBuilder
attr_reader :document
def initialize()
@document = {}
end
def convert_section(line)
line =~ /^#\s*(.+)$/
@section_name = $1
document[@section_name] = []
end
def convert_hashtag(line)
hashtags = line.split("#").reject {_1.strip.empty?}
document[@section_name] += hashtags
end
end
lines = File.readlines("markdown.md")
builder = DocumentBuilder.new
reader = MarkdownReader.new(builder)
reader.parse(lines)
p builder.document
=> {"Section 1"=>["hash1", "hash tag 2", "hashtag3"], "Section 2"=>["hash1", "hash tag 4", "hash tag2"]}
关于ruby - 在 ruby 中提取文档中的主题标签和部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74013157/