# 求教—— txt中 如何将 @@@link=xxx 替换为原词条内容

**URL:** <https://forum.freemdict.com/t/topic/14514>\
**Category:** 技术交流与词典编修\
**Created:** [2022 年8 月 7 日 04:51 UTC](https://forum.freemdict.com/t/topic/14514 "2022-08-07T04:51:44Z")\
**Posts on this page:** 4\
**Page:** 2

<div class="post-metadata">

作者： ![lyzhao](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/l/ba8739/32.png) [@lyzhao](https://forum.freemdict.com/u/lyzhao)\
发布日期： [2022 年8 月 11 日 08:23 UTC](https://forum.freemdict.com/t/topic/14514/24 "2022-08-11T08:23:30Z")

</div>

> [@surfactant](#):
>
> `RegExp('\r\n' + myEntry + '\r\n.+\r\n', '')`

你确定这个正则表达式没问题？为什么我一个都匹配不到

---

<div class="post-metadata">

作者： ![surfactant](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/s/dbc845/32.png) [@surfactant](https://forum.freemdict.com/u/surfactant)\
发布日期： [2022 年8 月 11 日 08:31 UTC](https://forum.freemdict.com/t/topic/14514/25 "2022-08-11T08:31:56Z")

</div>

> [@surfactant](#):
>
> RegExp

这是我的古董文本编辑器支持的js脚本，跑过没问题。你确定 python 里 RegExp() 这个函数吗？

---

<div class="post-metadata">

作者： ![lyzhao](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/l/ba8739/32.png) [@lyzhao](https://forum.freemdict.com/u/lyzhao)\
发布日期： [2022 年8 月 12 日 04:15 UTC](https://forum.freemdict.com/t/topic/14514/26 "2022-08-12T04:15:46Z")

</div>

RegExp对应的是Python里的re.compile函数？那里我不编译成正则表达式模式行不行？还有你这个代码是在什么操作系统下跑通的？我在Windows里面是不是应该把\r\n换成\n?另：在你的设定中,.能不能匹配到换行符？

```auto
import re

code = input("请输入编码方式：")
source = open('input.txt', 'r', encoding=code)
content = source.read()
source.close()
content = "\n" + content + "\n" # 当前文本文件的完整内容

myEntry = "" # 一个词头
myContent = "" # 一条释义

while re.findall(r'\n@@@LINK=.+\n', content, re.S):
    myEntry = re.findall(r'\n@@@LINK=.+\n', content,re.S)[0]
    myEntry = re.sub(r'@@@LINK=', '', myEntry)
    myEntry = re.sub(r'\n', '', myEntry)
    myContent = re.findall('\n' + myEntry + '\n.+\n', content, re.S)[0] # 这行的正则表达式有误
    myContent = re.sub('\n' + myEntry + '\n', '\n', myContent)
    content = re.sub('\n@@@LINK=.+\n', myContent, content)
output_file = open('output.txt', 'w+', encoding=code)
output_file.write(content)
output_file.close()

```

---

<div class="post-metadata">

作者： ![surfactant](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/s/dbc845/32.png) [@surfactant](https://forum.freemdict.com/u/surfactant)\
发布日期： [2022 年8 月 12 日 04:21 UTC](https://forum.freemdict.com/t/topic/14514/27 "2022-08-12T04:21:02Z")

</div>

> [@lyzhao](#):
>
> RegExp对应的是Python里的re.compile函数？那里我不编译成正则表达式模式行不行？

这我不知道，我想那点代码虽然是js的，但是意思应该一看就懂吧  
看来你没找到python里面生成包含字符串变量的正则表达式的函数

> [@lyzhao](#):
>
> 你这个代码是在什么操作系统下跑通的？

在 Windows 下的一个小众古董编辑器中的 js 脚本

> [@lyzhao](#):
>
> 是不是应该把\r\n换成\n?另：在你的设定中,.能不能匹配到换行符？

我碰到的大多数文件都是用 \r\n 就能匹配换行符，有些可能只要 \r 或 \n，这里面有个说法的现在忘了

测试  
 ![image](https://forumcdn.freemdict.com/uploads/default/original/3X/1/b/1b15fa6bb6d50c6abf4f2eee9795c46d28d9a693.png)

[上一页](https://forum.freemdict.com/t/topic/14514.md?page=1)
