使用 Python 仅知道开头和最后一个单词来替换文本部分 [英] Replace section of text with only knowing the beginning and last word using Python

查看:26
本文介绍了使用 Python 仅知道开头和最后一个单词来替换文本部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,当你只知道开始和结束单词时,可以在文档中剪切一段文本吗?

例如,使用权利法案作为示例文档,搜索Amendment 3"并删除所有文本,直到您点击Amendment 4",而实际上并不知道或关心两个端点之间存在什么文本.

我问的原因是,当我将其他 Python 程序上传到客户端的计算机时,我想使用此 Python 脚本来修改它们——删除#chop-begin"注释之间存在的代码部分" 和 "#chop-end".我不希望客户在不为更好的代码版本付费的情况下访问所有功能.

解决方案

你可以使用 Python 的 re 模块.

我编写了这个示例脚本来删除文件中的代码部分:

导入重新# 创建正则表达式模式斩 = re.compile('#chop-begin.*?#chop-end', re.DOTALL)# 打开文件f = open('数据', 'r')数据 = f.read()f.close()# 在#chop-begin 和 #chop-end 之间截取文本data_chopped =chop.sub('', 数据)# 保存结果f = 打开('数据','w')f.write(data_chopped)f.close()

In Python, it possible to cut out a section of text in a document when you only know the beginning and end words?

For example, using the bill of rights as the sample document, search for "Amendment 3" and remove all the text until you hit "Amendment 4" without actually knowing or caring what text exists between the two end points.

The reason I'm asking is I would like to use this Python script to modify my other Python programs when I upload them to the client's computer -- removing sections of code that exists between a comment that says "#chop-begin" and "#chop-end". I do not want the client to have access to all of the functions without paying for the better version of the code.

解决方案

You can use Python's re module.

I wrote this example script for removing the sections of code in file:

import re

# Create regular expression pattern
chop = re.compile('#chop-begin.*?#chop-end', re.DOTALL)

# Open file
f = open('data', 'r')
data = f.read()
f.close()

# Chop text between #chop-begin and #chop-end
data_chopped = chop.sub('', data)

# Save result
f = open('data', 'w')
f.write(data_chopped)
f.close()

这篇关于使用 Python 仅知道开头和最后一个单词来替换文本部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆