ruby - 解析文本文件以获取文本选择
问题描述
我有一个文本文件,我想在其中获取一段文本,以便将其放入两个数组中,一个是成分,另一个是方向。
对于成分,我可以做如下的事情,但我不能保证它的完整性。
ingredients = []
list.each_line do |l|
ingredients << l if l =~ /\d\s?\w.*/
end
这是文本块:
635860
581543
2011-03-21T13:50:10Z
Image:black bean soup.jpg|right|Mexican Black Bean Soup
== Ingredients ==
1lb black beans
2 tbsp extra-virgin olive oil
2 onions, large, diced
6 cloves garlic, minced
1 cup tomato, peeled, seeded, and chopped (fresh or canned)
1 sprig epazote, fresh or dried (optional)
1 tbsp chipotle pepper|chipotle chiles, canned, chopped (or ¼ tsp cayenne)
1 tsp cumin, ground
1 tsp coriander seed|coriander, ground
2 tsp salt
== Directions ==
Soak the black beans for 2 hours and drain.
In a deep pot, heat the olive oil over medium heat.
Add the onions and cook about 5 minutes.
Until translucent.
Add the black beans|beans, garlic, and 6 cups cold water.
Bring to a boil, skimming any foam that rises to the surface.
Reduce to a simmer.
In an hour or when the black beans|beans are soft, add the tomato, epazote, chipotle chile peppers|chile, cumin, coriander, and salt.
Continue cooking until the black beans|beans start to break down and the broth begins to thicken.
Taste for seasoning and add salt and pepper if needed.
If you’re serving this soup immediately, you may want to thicken it by puréeing a cup or two of the black beans|beans in a blender or food processor and then recombining them with the rest of the soup.
The soup will thicken on its own if refrigerated overnight.
Category:Black bean Recipes
Category:Chile pepper Recipes
Category:Chipotle pepper Recipes
Category:Epazote Recipes
Category:Mexican Soups
Category:Tomato Recipes
bx0ztz9xbf8qr9z4gwkad26u6q3hly3
解决方案
我在这里要做的不是尝试匹配您可能无法控制的数据,而是尝试匹配看起来您可能可以控制的数据。具体来说,它在我看来就像线条== Ingredients ==
,== Directions ==
并且Category:Tomato Recipes
可能是文件格式的一部分,不是用户输入的。因此,每当您看到如下所示的行时,我都会将文本拆分:
sections = list.each_line.slice_before do |line|
line.match?(/\A(==|[a-zA-Z]+:)/)
end.entries
然后你可以只assoc
从组中取出数据:
puts sections.assoc("== Ingredients ==\n")
puts '---'
puts sections.assoc("== Directions ==\n")
这仍然有一些缺陷(如果用户输入Note: Preheat oven first
的内容作为方向的一部分,这最终会分裂,认为它是元数据),但应该是向前迈出的一大步,并且可以从这里进行调整。
推荐阅读
- oracle - 按行数更新 Oracle 表
- rollup - rollupjs 可以将 iframe-resizer 作为外部支持吗?
- json - Keycloak/Wildfly 如何将所有控制台日志配置为 JSON 格式
- c# - EF6 - 获取所有相关的孩子
- java - Java与Linux之间的Sha256校验和差异
- postgresql - 将值与日期范围之间的行相乘
- sql - 联合所有但只保留 T-SQL 中一张表的重复项
- c# - How to replace values smaller than zero with zero in a collection using LINQ
- reactjs - 如果作为参数传递并分配给变量,则 TypeScript 中的 React 组件;TS2604:JSX 元素类型没有任何构造或调用签名
- python - How to generate new list for each element of existing list (which is also generated)?