字符串操作 - jython 中的 re.sub

发布于 2024-08-16 03:34:42 字数 515 浏览 5 评论 0原文

假设我有一个像这样的字符串“这是一个声明” 如果我想搜索字符串并将其替换为“this ** a statements”

字符串,以搜索 this is a statements 、 this si a statements 、 this ia statements 以及任何组合,将它们转换为此 trim一份声明 即对于 this 和; 之间的任何单词组合语句将其替换为 trim 对于另一组,将 fun 替换为 notfun

所以这个程序

import re
file=open('file','r+')
search=re.sub('this \(a_zA_Z0_9)+ a statement','\1trim',file),('this is fun','this is notfun',file)
file.close()

有些不对劲,因为文件中没有任何变化。

谢谢大家。

Let say i have a string like this 'this is a statement'
and if i want to search and replace string with this 'this ** a statement'

string to search for this is a statement , this si a statement , this i a statement and any combination convert them into this trim a statement
i.e for any word combination between this & a statement replace it with trim
for another set replace fun to notfun .

so this is the program

import re
file=open('file','r+')
search=re.sub('this \(a_zA_Z0_9)+ a statement','\1trim',file),('this is fun','this is notfun',file)
file.close()

something is not right as nothing is getting changed in the file.

thanks everyone.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见终念 2024-08-23 03:34:42

re.sub 不适用于文件,它适用于字符串。您需要将文件的内容读入字符串,然后使用 re.sub 更改字符串,然后将修改后的字符串写回到文件中。

一个简单的例子:

text = open("myfile.txt").read()
# This is your original re.sub call, but I'm not sure it really does what you want.
text = re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text)
text = re.sub('this \(a_zA_Z0_9)+ another replacement', 'some other thing', text)
open("myfile.txt", "w").write(text)

re.sub doesn't work on files, it works on strings. You need to read the contents of the file into a string, then use re.sub to change the string, then write the modified string back to the file.

A simple example:

text = open("myfile.txt").read()
# This is your original re.sub call, but I'm not sure it really does what you want.
text = re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text)
text = re.sub('this \(a_zA_Z0_9)+ another replacement', 'some other thing', text)
open("myfile.txt", "w").write(text)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文