gpt4 book ai didi

parsing - Haskell:遍历字符串/文本文件

转载 作者:行者123 更新时间:2023-12-02 14:21:40 25 4
gpt4 key购买 nike

我正在尝试读取脚本文件,然后处理并将其输出到 html 文件。在我的脚本文件中,只要有 @title(这是一个标题),我就会在我的 html 中添加标签 [header] 这是一个标题 [/header]输出。所以我的做法是先读取脚本文件,将内容写入字符串,处理字符串,然后将字符串写入html文件。

为了识别@title,我需要逐个字符地读取字符串中的字符。当我读取“@”时,我需要检测下一个字符以查看它们是否是标题。

问题:如何在 Haskell 中遍历字符串(这是一个字符列表)?

最佳答案

例如,您可以使用简单的递归技巧

findTag [] = -- end of list code.
findTag ('@':xs)
| take 5 xs == "title" = -- your code for @title
| otherwise = findTag xs
findTag (_:xs) = findTag xs

所以基本上,如果下一个字符(列表头)是“@”,则只需进行模式匹配,然后检查接下来的 5 个字符是否形成“标题”。如果是这样,您可以继续解析代码。如果下一个字符不是“@”,您只需继续递归。一旦列表为空,您就会到达第一个模式匹配。

其他人可能有更好的解决方案。

我希望这能回答您的问题。

编辑:

为了获得更大的灵 active ,如果您想查找特定标签,可以这样做:

findTag [] _ = -- end of list code.
findTag ('@':xs) tagName
| take (length tagName) xs == tagName = -- your code for @title
| otherwise = findTag xs
findTag (_:xs) _ = findTag xs

如果你这样做的话就这样

findTag text "title"

您将专门查找标题,并且可以随时将标记名更改为您想要的任何内容。

另一个编辑:

findTag [] _ = -- end of list code.
findTag ('@':xs) tagName
| take tLength xs == tagName = getTagContents tLength xs
| otherwise = findTag xs
where tLength = length tagName
findTag (_:xs) _ = findTag xs

getTagContents :: Int -> String -> String
getTagContents len = takeWhile (/=')') . drop (len + 1)

说实话,事情变得有点困惑,但实际情况是这样的:

首先删除 tagName 的长度,然后再删除左括号的长度,最后使用 takeWhile 获取字符直到右括号为止。

关于parsing - Haskell:遍历字符串/文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com