Python中文
首页
教程
问答
标签
搜索
登录
注册
python:使用variab替换精确匹配
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>程序读取文本文件并基于变量替换匹配的单词。问题是非精确匹配正在被替换。所以如果我把“the”改成“da”,那么“then”就变成了“dan”</p> <pre><code>for fn in os.listdir('.'): if os.path.isfile(fn): if fn.endswith(".txt"): s = open(fn).read() for i in skills: link = skills[i] s = s.replace(i, "<a href=\"%s\">%s</a>" %(link,i), 1) print "%s updated" %fn f = open(fn, 'w') f.write(s) f.close() </code></pre> <p>问题出在<code>s = s.replace(i, "<a href=\"%s\">%s</a>" %(link,i), 1)</code>,其中s.replace()中的第一个参数是包含要匹配的字符串的变量。</p> <p>我试过使用单词边界<code>s = s.replace(r'\b'+i+r'\b', "<a href=\"%s\">%s</a>" %(link,i), 1)</code></p> <p>将<code>i</code>处的值格式化为一个新变量:<code>regex = r'\b' + i + r'\b'</code>,并使用<code>regex</code>作为<code>s.replace</code>中的第一个参数,但它不起作用。</p> <p>注意。<code>skills</code>是一个包含单词/链接对的字典</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>如果<code>string</code>是读取文件的内容:</p> <pre><code>string = string.replace('the ', 'da ') # space ensures then isn't replaced </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
plt.savefig不会覆盖现有文件
4 回答
plt.savefig不保存图像
2 回答
plt.savefig在jupyter笔记本中不起作用
1 回答
plt.savefig在从另一个fi调用时停止工作
4 回答
plt.savefig在调用plt.show之前保存空数字
10 回答
plt.save不创建png文件
3 回答
plt.scatter overlay分类数据帧列
3 回答
Plt.Scatter:如何添加title、xlabel和ylab
3 回答
plt.scatter()绘图与Matplotlib中的plt.plot()绘图类似
9 回答
plt.scatter错误'NoneType'对象在成功运行后没有属性'sqrt'
5 回答
plt.set_title()中的标题字符串有误
2 回答
plt.show()
6 回答
plt.show()不在Jupyter笔记本上渲染任何内容
4 回答
plt.show()不打印plt.plot only plt.scatter
3 回答
plt.show()不显示三维散射图像
8 回答
plt.show()不显示任何内容
5 回答
plt.show()不显示数据,而是保留它供下一个图表使用(spyder)
2 回答
plt.show()使终端挂起
3 回答
plt.show()无法使用此代码
2 回答
plt.show()没有打开新的图形风
1 回答