40147

Replace section of text with only knowing the beginning and last word using Python

Question:

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.

Answer1:

You can use Python's <a href="http://docs.python.org/library/re.html" rel="nofollow">re</a> 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()

Answer2:

With data.txt

do_something_public() #chop-begin abcd get_rid_of_me() #chop-end #chop-beginner this should stay! #chop-begin do_something_private() #chop-end The rest of this comment should go too! but_you_need_me() #chop-begin last_to_go() #chop-end

the following code

import re class Chopper(object): def __init__(self, start='\\s*#ch'+'op-begin\\b', end='#ch'+'op-end\\b.*?$'): super(Chopper,self).__init__() self.re = re.compile('{0}.*?{1}'.format(start,end), flags=re.DOTALL+re.MULTILINE) def chop(self, s): return self.re.sub('', s) def chopFile(self, infname, outfname=None): if outfname is None: outfname = infname with open(infname) as inf: data = inf.read() with open(outfname, 'w') as outf: outf.write(self.chop(data)) ch = Chopper() ch.chopFile('data.txt')

results in data.txt

do_something_public() #chop-beginner this should stay! but_you_need_me()

Answer3:

Use <a href="http://docs.python.org/library/re.html" rel="nofollow">regular expressions</a>:

import re string = re.sub('#chop-begin.*?#chop-end', '', string, flags=re.DOTALL)

.*? will match all between.

Recommend

  • draw grid with cells of specific size over an image
  • ManagedBean Params not accepted and Bean seemingly not in scope
  • Affordable options for multi touch desktop device (To test apps on Windows phone 7 emulator)?
  • Print dynamic Excel page with changing content
  • Amazon S3 - How do I download objects owned by anonymous user?
  • Haskell: List Created Evaluating List Elements
  • How do I chomp a string if I have Perl 4?
  • Tracking screen recorder in windows app
  • Add spaces between words in spaceless string
  • Creating My Symmetric Key in C#
  • HttpListener.IsSupported is false on XP SP3
  • SonarQube: Cannot deactivate rule with missing quality profile
  • Remove changes from one element when event occurs on another element?
  • Spring Cloud Microservice Architecture Confusion
  • Remove final comma from string in vb.net
  • Transactional Create with Validation in ServiceStack Redis Client
  • Custom Tabgroup Appcelerator
  • $wpdb not working in file of WordPress plugin
  • Handling un-mapped Rest path
  • PHP - How to update data to MySQL when click a radio button
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • output of program is not same as passed argument
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Deserializing XML into class C#
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Why winpcap requires both .lib and .dll to run?
  • Apache 2.4 - remove | delete | uninstall
  • Arrays break string types in Julia
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • How to include full .NET prerequisite for Wix Burn installer
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • How do you join a server to an Active Directory (domain)?
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • costura.fody for a dll that references another dll
  • git trying to push non-existent file … after clearing cache
  • java string with new operator and a literal
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize