473,325 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Regarding searching of strings

i am a beginner in Python. I have a query.

I have a .txt file which has entries in the following manner:

Name: John
Age: 21

Name: Paul
Age:23

I need to search for the string "Name" and display all the values corresponding to the string that i am searching for. In this case the result should be John and Paul.
I am a bit confused with the re.search() function.

Kindly guide me regarding the same.

Regards,
BK
Nov 8 '06 #1
6 1492
fuffens
38
If names always start with Name: in your file and is separated by a white space then this should do it

Expand|Select|Wrap|Line Numbers
  1. file = open('name.txt', 'r')
  2. for line in file:
  3.     if line.startswith('Name:'):
  4.         name = line.split()[1]
  5.         print name
  6. file.close()
Use regular expressions for more compex search operations. Here you only need to find Name: so you can use normal string operations like startswith() or find().

Best regards
/Fredrik
Nov 8 '06 #2
bvdet
2,851 Expert Mod 2GB
i am a beginner in Python. I have a query.

I have a .txt file which has entries in the following manner:

Name: John
Age: 21

Name: Paul
Age:23

I need to search for the string "Name" and display all the values corresponding to the string that i am searching for. In this case the result should be John and Paul.
I am a bit confused with the re.search() function.

Kindly guide me regarding the same.

Regards,
BK
I wrote a script to run in SDS/2 (software for structural steel detailing) that does something similar. The input file format is:
Origin:0.0,0.0
Direction:-90.0
41-5
42-8
......additional offset dimensions

Origin:0.0,0.0
Direction:0.0
1-11 1/2
1-0 1/2
.......additional offset dimensions
The object of this script is to layout building grid lines in a plan view of the 3D model. Here's the code:
Expand|Select|Wrap|Line Numbers
  1. def run_script():
  2.     try:
  3.         from param import ResponseNotOK, Units, Dialog, Warning, dim
  4.         from macrolib.ExceptWarn import formatExceptionInfo
  5.         from macrolib.PolarPt import polar_pt_plan
  6.         from point import Point
  7.         from job import JobName
  8.         from cons_line import ConsLine
  9.         import os
  10.         import string
  11.         Units("feet")
  12.  
  13.         #####################################    
  14.         def gridAdd(pt, dir, cons_color="Cyan"):
  15.             # construction line begin
  16.             cl2 = ConsLine()
  17.             cl2.pt1 = pt
  18.             cl2.angle = dir
  19.             cl2.pen = cons_color
  20.             cl2.add()
  21.             # construction line end
  22.         ####################################
  23.  
  24.         ## Dialog Box ######################
  25.         dlg1 = Dialog("Building Grid Lines in Plan")
  26.         dlg1.group_title("Import Grid Line File")
  27.         dlg1.file('import_file', os.path.join(os.getcwd(), "jobs", JobName(), "macro", "TownCtrGrids.txt"), "Enter file name or browse       ")
  28.         dlg1.menu('cons_color', ("Blue", "Green", "Yellow", "Magenta", "Red", "White", "Cyan"), "Blue", "Construction line color")
  29.  
  30.         try:
  31.             dlg1.done()
  32.         except ResponseNotOK:
  33.             raise
  34.  
  35.         # Import grid line file
  36.         try:
  37.             f = open(dlg1.import_file, "r")
  38.         except IOError, e:
  39.             # unable to open file
  40.             Warning("Unable to open file: %s" % (e))
  41.  
  42.         for item in f:
  43.             if "origin" in string.lower(item):
  44.                 ptx, pty = item.split(':')[1].split(",")                    
  45.                 gridWP = Point(dim(ptx.strip()), dim(pty.strip()), 0.0)
  46.             elif "direction" in string.lower(item):
  47.                 gridOffset = 0.0
  48.                 gridDir = dim(item.split(':')[1].strip())
  49.                 gridAdd(gridWP, gridDir, dlg1.cons_color)
  50.             else:
  51.                 if dim(item.strip()):
  52.                     gridOffset = gridOffset + dim(item.strip())
  53.                     gridAdd(polar_pt_plan(gridWP, gridOffset, gridDir + 90.0), gridDir, dlg1.cons_color)
  54.         f.close()
  55.     except:
  56.         Warning(formatExceptionInfo())
  57. ## END run_script() #########################
  58. if __name__ == '__main__':
  59.     try:
  60.         run_script()
  61.     finally:
  62.         del run_script
Thanks to this list for the pointers received!
Nov 8 '06 #3
If names always start with Name: in your file and is separated by a white space then this should do it

Expand|Select|Wrap|Line Numbers
  1. file = open('name.txt', 'r')
  2. for line in file:
  3.     if line.startswith('Name:'):
  4.         name = line.split()[1]
  5.         print name
  6. file.close()
Use regular expressions for more compex search operations. Here you only need to find Name: so you can use normal string operations like startswith() or find().

Best regards
/Fredrik

Hi,

As far as my understanding goes, its only when it starts with "Name:" i can use the code snippet provided. But what if i need to search for the string "Name:" and display the values corresponding to it.

e.g if i have a format like mentioned below:

### Name: John
Age: 23

*** Name: Paul
Age: 24

Here how do i go about searching for the string "Name:" and displaying all the matching content for the string on the screen.

Kindly clarify my doubt.

Thanks,
BK
Nov 9 '06 #4
fuffens
38
This will do it...

Expand|Select|Wrap|Line Numbers
  1. file = open('name.txt', 'r')
  2. for line in file:
  3.     if line.find('Name:') >= 0:
  4.         name = line.split()[-1]
  5.         print name
  6. file.close()
You can use find to check if a string is included in a string. It will return a negative number if not included. You can still use split() to extract the name. [-1] will give you the last element of the split list.

/Fredrik
Nov 9 '06 #5
This will do it...

Expand|Select|Wrap|Line Numbers
  1. file = open('name.txt', 'r')
  2. for line in file:
  3.     if line.find('Name:') >= 0:
  4.         name = line.split()[-1]
  5.         print name
  6. file.close()
You can use find to check if a string is included in a string. It will return a negative number if not included. You can still use split() to extract the name. [-1] will give you the last element of the split list.

/Fredrik

Thanks a lot Fredrik. It was very helpful

Thanks,
BK
Nov 9 '06 #6
bvdet
2,851 Expert Mod 2GB
This works also:
Expand|Select|Wrap|Line Numbers
  1. if 'Name' in line:
Nov 9 '06 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

18
by: jblazi | last post by:
I should like to search certain characters in a string and when they are found, I want to replace other characters in other strings that are at the same position (for a very simply mastermind game)...
6
by: akash shetty | last post by:
hi, im developing a code which requires searching a large database(bioological) for certain patterns.the size of the file is 3.5GB . the search pattern is a ten letter string.the database...
4
by: tgiles | last post by:
Hi, all. Another bewildered newbie struggling with Python goodness. This time it's searching strings. The goal is to search a string for a value. The string is a variable I assigned the name...
12
by: rbt | last post by:
Not really a Python question... but here goes: Is there a way to read the content of a PDF file and decode it with Python? I'd like to read PDF's, decode them, and then search the data for certain...
3
by: googleboy | last post by:
Hi there. I have defined a class called Item with several (about 30 I think) different attributes (is that the right word in this context?). An abbreviated example of the code for this is: ...
38
by: edu.mvk | last post by:
Hi I am using strcpy() in my code for copying a string to another string. i am using static char arrays. for the first time it is exected correctly but the second time the control reaches...
8
by: Allan Ebdrup | last post by:
What would be the fastest way to search 18,000 strings of an average size of 10Kb, I can have all the strings in memory, should I simply do a instr on all of the strings? Or is there a faster way?...
1
by: DLN | last post by:
Hello all, I have a quick question regarding how best to use static strings in my C# code that I'm hoping someone can help me with. Is there any advantage/disadvantage from a performance...
4
by: Hunk | last post by:
Hi I have a binary file which contains records sorted by Identifiers which are strings. The Identifiers are stored in ascending order. I would have to write a routine to give the record given...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.