gpt4 book ai didi

html - 使用TCL在html文件中插入数据

转载 作者:可可西里 更新时间:2023-11-01 13:10:45 26 4
gpt4 key购买 nike

这是我的 html 文件:

<head>
<title>Reading from text files</title>
</head>
<body>
<h3>Starting space</h3>
<ul>
<li></li>
</ul>
<h3>ending space</h3>
<ul>
</body>
</html>

我想使用 tcl 和正则表达式编辑此 html 文件。但我想在特定位置编辑它,即 Starting spaceending space 之间。在这些点之间,我想添加各种列表项。

<li> First </li>

等。我编写了 tcl 脚本来打开这个文件,并尝试打印出这两个位置之间的数据,以便我以后可以对其进行编辑。但我不能那样做。你能指出我哪里错了吗?

Tcl 脚本

proc edit_html {release} {
set fp [open $release r]
set para [read -nonewline $fp]
close $fp
set line_read [regexp -nocase -lineanchor -inline -all -- {^\s*?Starting space\s*?.*?ending space} $para]
foreach line_read $line_read {
regexp -nocase -- {^\s*?Starting space\s*?.*?ending space} $line_read - tag value
puts $value

}
}
edit_html [lindex $argv 0]

我不确定这个正则表达式哪里出错了。一旦找到位置,我应该如何编辑它?有什么要注意的吗?就像我应该把文件指针带到 thr 吗?

最佳答案

要编辑一个文本文件,你需要把它加载到内存中,然后再写出来;你不能通过写回同一个文件来流式传输。你可以写一个简单的方法来直接选择要替换的文本,你可以使用 regsub 作为它的核心,但这在这里是不可能的,因为你正在匹配区域两侧的文本匹配。因此,对于您正在查看的那种编辑,您需要的是指示要替换的第一个字符所在位置的字符串(即文件内容)的索引,以及要替换的最后一个字符的索引替换。

幸运的是,获取索引很容易。您可以使用 regexp -indices 或使用 string first/string last

# Read the file; standard stanza
set f [open $theFilename]
set data [read $f]
close $f

# Find the markers
regexp -indices {<h3>Starting space</h3>\n<ul>\n} $data start
regexp -indices {\n</ul>\n<h3>ending space</h3>} $data end

# We now need to offset the ends by one in each direction (we want stuff between)
set start [expr {[lindex $start 1] + 1}]
set end [expr {[lindex $end 0] - 1}]

# Now we can generate the replacement...
set replacement ""
foreach item ... {
append replacement "<li>...</li>\n"
}

# ... and insert it
set data [string replace $data $start $end $replacement]

# ... and write it out (without the extra newline; we've enough already)
set f [open $theFilename "w"]
puts -nonewline $f $data
close $f

或者,您可以在将内容写回文件时进行替换。

# Read the file; standard stanza
set f [open $theFilename]
set data [read $f]
close $f

# Find the markers
regexp -indices {<h3>Starting space</h3>\n<ul>\n} $data start
regexp -indices {\n</ul>\n<h3>ending space</h3>} $data end

# Generate the replacement text
set replacement ""
foreach item ... {
append replacement "<li>...</li>\n"
}

# Write everything out
set f [open $theFilename "w"]
puts -nonewline $f [string range $data 0 [lindex $start 1]]
puts -nonewline $f $replacement
puts -nonewline $f [string range $data [lindex $end 0] end]
close $f

关于html - 使用TCL在html文件中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825769/

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