Regex Group case change
Hello Everyone,
I want to change the case on input string i was able to match using python
regex but couldn't find the way to change the case.
For example string:
Input: 7Section Hello Jim
output: 7Section hello Jim
I was doing if statment with regex
if re.match("(\d+\w* )(Hello)( \w+)",string)):
print(r"(\d+\w* )(Hello)( \w+)","\1\2.lower()\3",string)
Output was
7Section \2.lower() Jim
Above one is one of the regex i have in function, i have total 6 regex patterns
and i want to keep all in this if elif else statment. It is matching, but can
someone advise how to replace Hello to hello?
Thanks
--
https://mail.python.org/mailman/listinfo/python-list
Re: Regex Group case change
import re
import os
import sys
#word = "7 the world" # 7 The world
#word = "Brian'S" # Brian's
#word = "O'biran"# O'Brian
#word = "Stoke-On-Trent" # Stoke-on-Trent; here i need to lower the case of
middle word(i.e -On-)
def wordpattern(word):
output = ''
if re.match("^\d+|w*$",word):
output = word.upper()
elif re.match("\w+\'\w{1}$",word):
output = word.capitalize()
elif re.match("(\d+\w* )(Hello)( \w+)",word))
group(1)group(2).title()group(3)
else:
output.title()
On Thursday, October 1, 2020 at 10:53:16 PM UTC+1, [email protected] wrote:
> On 01Oct2020 12:41, Raju wrote:
> >I want to change the case on input string i was able to match using
> >python regex but couldn't find the way to change the case.
> >
> >For example string:
> >Input: 7Section Hello Jim
> >output: 7Section hello Jim
> >
> >I was doing if statment with regex
> >
> >if re.match("(\d+\w* )(Hello)( \w+)",string)):
> > print(r"(\d+\w* )(Hello)( \w+)","\1\2.lower()\3",string)
> >
> >Output was
> >7Section \2.lower() Jim
> >Above one is one of the regex i have in function, i have total 6 regex
> >patterns and i want to keep all in this if elif else statment. It is
> >matching, but can someone advise how to replace Hello to hello?
> Please paste the _exact_ code you're using to produce the problem. I do
> not believe the code above generates the output you show. I imagine
> there's som kind of regexp replacement call in the real code.
>
> There's a few things going on in the code above which will cause
> trouble:
>
> Be consistent using "raw strings", which look like r"...". Normal
> Python string recognise a variety of backslash escaped things, like \n
> for a newline character. The purpose of a raw string is to disable that,
> which is important with regular expressions because they also use
> backslash escapes such as \d for a digit. Try to _always_ use raw
> strings when working with regular expressions.
>
> Your print() call _looks_ like it should be printing the result of a
> regexp substitute() function call, based on the "\1\2.lower()\3" in the
> second field. The substitute() syntax does not support embedding str
> methods in the result, so the .lower() will just be written out
> directly. To do more complicated things you need to pull out the matched
> groups and work with them separately, then assemble your desired result.
>
> You do not keep the result of the re.match call here:
> if re.match("(\d+\w* )(Hello)( \w+)",string)):
> Traditionally one would write:
>
> m = re.match("(\d+\w* )(Hello)( \w+)",string))
> if m:
>
> and in recent Python (3.8+) you can write:
>
> if m := re.match("(\d+\w* )(Hello)( \w+)",string)):
>
> This preserves the result fo the match in the variable "m", which you
> will require if you want to do any work with the result, such as
> lowercasing something.
>
> The matches components of the regexp are available via the .group()
> method of the match result. So:
>
> m.group(1) == "7Section"
> m.group(2) == "Hello"
>
> and to print "Hello" lowercased you might write:
>
> m.group(2).lower()
>
> Since this looks much like homework we will leave it to you to apply
> this approach to your existing code.
>
> Cheers,
> Cameron Simpson
--
https://mail.python.org/mailman/listinfo/python-list
about computer tips inonline click here
http://www.moneymaking4.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
click here more tips in online about software
http://www.moneymaking4.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
get paid on free offers
http://www.moneymaking4.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
click heremore dollar
http://www.moneymaking4.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
How to manipulate a contents of file as record structures
I have a text file containing the following alphanumerals. aa2255 hh11dpdpdpdp22 kkk21lokolkolko33 . I need to read the contents as single line, one after the other and append the sum of digits at the end. aa225577 hh11dpdpdpdp2233 kkk21lokolkolko3354 What would be a simple way to achieve this ? CK Raju -- http://mail.python.org/mailman/listinfo/python-list
Re: How to manipulate a contents of file as record structures
On Sat, Jan 31, 2009 at 4:19 PM, Gabriel Genellina wrote: > for line in f: > do_something_with(line) Thanks a lot. CK Raju -- http://mail.python.org/mailman/listinfo/python-list
Help required to read and print lines based on the type of first character
Hi,
I am a beginner in Python. In fact, beginner to coding/ scripting.
Here is a scenario, I need to code. Need your help on this:
A script that
1. Reads from a file (may be a local file say test.txt)
2. And, if the line begins with a "#", should print the line one time
3. if the line has "##", should print the line 2 times,
4. And, if there are "###" in the beginning of the line, should print the
same line 3times,
5. And, if the line contains "" or more "#"'s, then print as "an
invalid line"
6. if the line contains no "#" then print "looks like a code line"
For this as far the info I could understand,
- We need to use open('TextFile.txt') function
- Need to start a While loop/ For in loop
- By some means individually read every single line and check for the
above conditions
In this regard, I wish you could guide on what kind of syntax/ structure/
commands to use.
Thanks
Abhi
--
http://mail.python.org/mailman/listinfo/python-list
RE: Help required to read and print lines based on the type of first character
Thank you for the suggestions.
Some little reading gave the idea and it works well too. :)
Here is the code:
fileIN = open("test.txt")
count = 0
for line in fileIN:
data= line
if '' in data:
count = 4
elif '###' in data:
count = 3
elif '##' in data:
count = 2
elif '#' in data:
count = 1
elif data.find('#') == -1:
count = 0
if (count == 0):
print data + '\nlooks like a code line...\n'
elif(count== 4):
print data + '\ninvalid line!\n'
elif count>=1:
for i in range(0, count):
print data
Thanks,
R Abhinayaraj
-Original Message-
From: [email protected] [mailto:[email protected]]
Sent: Thursday, March 05, 2009 10:41 AM
To: Raju, Abhinayaraj
Cc: [email protected]
Subject: Re: Help required to read and print lines based on the type of first
character
De: "[email protected]"
> I am sorry to that I am not able to fully grasp it. Could you help me with
> some more details?
> How can I identify each line and utilize the interactive interpreter?
You really should read the tutorial at http://docs.python.org/tut
(or any other introductory text; see http://wiki.python.org/moin/BeginnersGuide
for more references)
To open the interpreter, just type "python" (no quotes; to execute) on
the command prompt.
--
Gabriel Genellina
Yahoo! Cocina
Recetas prácticas y comida saludable
http://ar.mujer.yahoo.com/cocina/
--
http://mail.python.org/mailman/listinfo/python-list
RE: Help required to read and print lines based on the type of first character
Thank you so much for your guidance, Bruno.
This should help me in a long way.
Here is the code I have written.
path = raw_input("\nEnter location eg. c:/buffer/test.txt : \n")
fileIN = open(path)
count = 0
for line in fileIN:
data= line
if '' in data:
count = 4
elif '###' in data:
count = 3
elif '##' in data:
count = 2
elif '#' in data:
count = 1
elif data.find('#') == -1:
count = 0
if (count == 0 and data!=""):
print data + '\nlooks like a code line...\n'
elif(count== 4):
print data + '\ninvalid line!\n'
elif count>=1:
for i in range(0, count):
print data
Thanks
Abhi
-Original Message-
From: Bruno Desthuilliers [mailto:[email protected]]
Sent: Thursday, March 05, 2009 6:50 PM
To: [email protected]
Subject: Re: Help required to read and print lines based on the type of first
character
(answering to the OP)
> En Wed, 04 Mar 2009 07:36:01 -0200, escribió:
>
>> I am a beginner in Python. In fact, beginner to coding/ scripting.
>>
>> Here is a scenario, I need to code. Need your help on this:
Your first task here should be to refine the specs - too much
ambiguities in it:
>> A script that
>> 1. Reads from a file (may be a local file say test.txt)
reads what ? The whole content ? A (yet unspecified) portion ? etc...
>> 2. And, if the line
which line ?
>> begins with a "#", should print the line one
>> time
" yadda" begins with a "#". So according to this rule, it should be
printed once.
>> 3. if the line has "##", should print the line 2 times,
" yadda" 'has' (contains) "##", so it should be printed twice. But
it also _begins_ with a '#', so according to rule 2, it should be
printed once. Is the 'one time' in rule 2 supposed to mean 'at least
onces', or 'once and only once' ? In this last case, rule 3 contradicts
rule 2.
Also, "yadday ## woops" 'has' (contains) "##". According to rule 3, it
should be printed twice. Is that right ?
>> 4. And, if there are "###" in the beginning of the line, should
>> print the same line 3times,
" yadda" begins with "###", so it should be printed thrice. It also
contains "##" (cf rule 3) and starts with "#" (cf rule 2). How is this
rule supposed to be understood ?
>> 5. And, if the line contains "" or more "#"'s, then print as
>> "an invalid line"
" yadda" starts with '#', contains '##', and starts with '###'.
Which rule is supposed to apply here ?
>> 6. if the line contains no "#" then print "looks like a code line"
>>
The first step in programming is to get accurate, unambigous and
well-expressed specs. In the above case (I mean, at this level of
detail), "accurate, unambigous and well-expressed specs" are almost
pseudocode. Doing a bit of mind-reading (which is certainly *not* the
right thing to do - in real life, I'd just go back to the customer or
whoever handed me such specs to sort this out), I came out with the
following rewrite:
1. open a given file in text mode
2. read it line by line
3. for each line:
3.1. if the line contains/startswith (?) more than three '#':
print "an invalid line"
3.2. if the line starts with one, two or three '#':
print as many times the line as there are '#'
3.2 else (imply : the line contains no '#'):
print "looks like a code line"
So basically, you have your algorithm. Now you just need to find out how
to do each of these tasks in Python. That is :
a. how to open a file for reading in text mode (NB: 'text mode' may or
not makes sense, according to the OS)
b. how to iterate over the lines in this file once it's correctly opened
c. how to test for the presence and position of a given character /
substring in a string
d. how to "print" something from your program.
Good news: all this is pretty well documented. I'd say that the most
"tricky" part is c., since there's more than one possible solution, but
since it's about strings, looking for what features Python strings has
to offer, and trying them out in the interactive interpreter should
solve the problem very quickly.
HTH
--
http://mail.python.org/mailman/listinfo/python-list
RE: Help required to read and print lines based on the type of first character
-Original Message- From: Bruno Desthuilliers [mailto:[email protected]] Sent: Thursday, March 05, 2009 10:45 PM To: [email protected] Subject: Re: Help required to read and print lines based on the type of first character [email protected] a écrit : Please, don't top-post, and learn to quote & snip (if you don't know what top-posting is, google is your friend). > Thank you so much for your guidance, Bruno. > > This should help me in a long way. > > Here is the code I have written. > > path = raw_input("\nEnter location eg. c:/buffer/test.txt : \n") > fileIN = open(path) This will break if the file can't be opened (doesn't exist, is protected, whatever). > count = 0 'count' is used locally in the loop, so it shouldn't be set outside it. > for line in fileIN: > data= line > > if '' in data: > count = 4 > elif '###' in data: > count = 3 > elif '##' in data: > count = 2 > elif '#' in data: > count = 1 > elif data.find('#') == -1: This test is redundant. if the "'#' in data" evals to False, then data.find('#') is garanteed to return -1. > count = 0 > > > if (count == 0 and data!=""): the file iterator yields lines with the newline character included, so there's no way that data == "" (unless you explicitely remove the newline character yourself). Read doc for the strip method of string objects. Also, you don't need the parens. > print data + '\nlooks like a code line...\n' > elif(count== 4): > print data + '\ninvalid line!\n' > elif count>=1: > for i in range(0, count): > print data You didn't address my questions wrt/ specs clarifications. There's a *big* difference between *containing* a substring and *starting with* a substring. Hint: Python strings have a "startswith" method... Also and FWIW, since Python >= 2.5.2 (and possibly >= 2.5.0 - I let you check the docs), Python's strings have a count method too. Your code is not too bad for a beginner - I've done worse when I started -, but it doesn't really matches the specs (which is impossible FWIW given the ambiguities they contain, cf my previous post), and contains a couple of more or less useless or redundant tests which make it looks a bit like "programming by accident", and doesn't really uses Python's string handling features. HTH Bruno, Thanks once again. Yeah, the specification is that it should seek for the first character (sub string) and based on that it should take the decision. So this is "*starting with* a substring." Case only. And as far as your review comments are concerned, I need to have a look at that all those doc's you have mentioned. That should help. -Abhi -- http://mail.python.org/mailman/listinfo/python-list
Python to Perl transalators
Could anyone suggest whether there is any Python to Perl code convertors? I found one on the net viz. Perthon. But it wasn't really helping out. Thanks Agni -- http://mail.python.org/mailman/listinfo/python-list
RE: Python to Perl transalators
-Original Message- From: [email protected] [mailto:[email protected]] On Behalf Of Chris Rebert Sent: Wednesday, March 18, 2009 10:53 AM To: Raju, Abhinayaraj Cc: [email protected] Subject: Re: Python to Perl transalators 2009/3/17 : > Could anyone suggest whether there is any Python to Perl code convertors? > I found one on the net viz. Perthon. But it wasn’t really helping out. Why on earth would you want to? That'd be like translating Shakespeare into a bad rap song! Cheers, Chris -- I have a blog: http://blog.rebertia.com :-) I am just a beginner learning both the languages. Wondered if I can have some comparative understanding of both. Agni -- http://mail.python.org/mailman/listinfo/python-list
RE: Python to Perl transalators
-Original Message- From: Andre Engels [mailto:[email protected]] Sent: Wednesday, March 18, 2009 3:53 PM To: Raju, Abhinayaraj Cc: [email protected] Subject: Re: Python to Perl transalators On Wed, Mar 18, 2009 at 6:27 AM, wrote: > > -Original Message- > From: [email protected] [mailto:[email protected]] On Behalf Of Chris Rebert > Sent: Wednesday, March 18, 2009 10:53 AM > To: Raju, Abhinayaraj > Cc: [email protected] > Subject: Re: Python to Perl transalators > > 2009/3/17 : >> Could anyone suggest whether there is any Python to Perl code convertors? >> I found one on the net viz. Perthon. But it wasn’t really helping out. > > > Why on earth would you want to? That'd be like translating Shakespeare > into a bad rap song! > > > Cheers, > Chris > > -- > I have a blog: > http://blog.rebertia.com > > :-) > > I am just a beginner learning both the languages. Wondered if I can have some > comparative understanding of both. I think automatic translation would be a very bad way of getting understanding of both. Translating from another language to Python usually leads to very un-Pythonic code - syntactically correct and working Python, but not 'real' Python. I assume that translating from Python to Perl will lead to something similarly un-Perlish. -- André Engels, [email protected] Thanks Andre for your suggestions! Agni -- http://mail.python.org/mailman/listinfo/python-list
RE: Python to Perl transalators
Thanks Nick. The website content is impressive. Thanks Agni -Original Message- From: Nick Craig-Wood [mailto:[email protected]] Sent: Wednesday, March 18, 2009 9:00 PM To: [email protected] Subject: Re: Python to Perl transalators Armin wrote: > On Wednesday 18 March 2009 11:01:00 Boris Borcic wrote: > > Armin wrote: > > >> > > >> Why on earth would you want to? That'd be like translating Shakespeare > > >> into a bad rap song! > > >> > > > > > > lol, actually I would prefer a rap song over Shakespeare, so your analogy > > > doesn't work there ;) > > > > Why, some people do prefer Perl over Python, so what's wrong with the > > analogy ? > > > > That would mostly apply to people who haven't coded in Python for one reason > or another. Perhaps the OP is looking for something like this http://pleac.sourceforge.net/pleac_python/index.html Which is a sort of Rosetta stone for perl and python ;-) (The perl cookbook translated into python.) -- Nick Craig-Wood -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Help needed to resolve ImportError
Hi, We currently use VC6.0 and Python 2.2 for our project. As part of porting our project to VC2005 when i try to compile our application, it gives the following error Traceback (most recent call last): File "v:\Component\DS\scripts\messagebuilder\IL_Messagebuilder\test\test_IL_setget.py", line 20, in import IL_setget File "\Component\DS\scripts\messagebuilder\IL_messagebuilder\IL_setget.py", line 22, in import IL_IEbuilder File "\Component\DS\scripts\messagebuilder\IL_messagebuilder\IL_IEbuilder.py", line 11, in from MessageDictionary import * File "\Component\LS\LSPythonFiles\MessageDictionary.py", line 3, in import ScriptInterpreter ImportError: No module named ScriptInterpreter Basically, we are trying to import a VC compiled DLL into python script which generates another Python file. This issue doesnt occur in VC6.0 setup I have tried setting path variables and options like copying scriptInterpreter.dll to python installation path and so on. HOwever it doesnt work. Are there any compatibility issues between VC2005 and python 2.2? HOw can i resolve this. Your help is highly appreciated. Best Regards Venkat _ Drag n’ drop—Get easy photo sharing with Windows Live™ Photos. http://www.microsoft.com/india/windows/windowslive/photos.aspx-- http://mail.python.org/mailman/listinfo/python-list
Re: Hello
On Jul 9, 11:43 am, geremy condra wrote: > On Fri, Jul 9, 2010 at 1:08 PM, Dani Valverde wrote: > > Sorry, I forgot to mention that I am using Linux. In fact, my first test > > have been with gedit. Is there any way to directly run the Python code into > > the console? > > Gedit has a plugin that brings up a python intepreter. > Edit->Preferences->Plugins->python console I think. > > Geremy Condra Hi Dani, I started liking wingware ide, I used free version before my company finally bought a licensed version. Give it a try www.wingware.com Raju Angani -- http://mail.python.org/mailman/listinfo/python-list
