我问的原因是,当我将其他 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 patternchop = re.compile('#chop-begin.*?#chop-end', re.DOTALL)# Open filef = open('data', 'r')data = f.read()f.close()# Chop text between #chop-begin and #chop-enddata_chopped = chop.sub('', data)# Save resultf = open('data', 'w')f.write(data_chopped)f.close() 这篇关于使用 Python 仅知道开头和最后一个单词来替换文本部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 21:25