473,786 Members | 2,866 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regarding searching of strings

17 New Member
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 1506
fuffens
38 New Member
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 Recognized Expert Moderator Specialist
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
......additiona l offset dimensions

Origin:0.0,0.0
Direction:0.0
1-11 1/2
1-0 1/2
.......addition al 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
bkunjitam
17 New Member
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 New Member
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
bkunjitam
17 New Member
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 Recognized Expert Moderator Specialist
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
2517
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) for my pupils. This very simple thing does not seem simple at all. If I use strings, I cannot replace their parts (though I can use string.find for the searching). I think it is a bad idea that strings are not mutable, but I suspect that...
6
2242
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 consists of paragraphs. the code ive developed searches the data paragraphwise. (using xreadlines). but this takes an awful amt of time.(abt 7 mins) is there anyway to speed this up.
4
1808
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 'myvar'. however, it doesn't seem to be seeing it... Here's a snippet. import re # list of items to search... mylist = # my variable I want to search with...
12
4347
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 strings. Thanks, rbt
3
1867
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: class Item(object): def __init__(self, height, length, function): params = locals()
38
2734
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 then the SEGMENTATION FAULT is occuring. Please tell me what are all the cases this problem may occur if we use strcpy().
8
1875
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? I would like to have a kind of search like google where you can enter several words to search for, guess that calls for a regular expression "word1|word2|word3|...". Is there any kind of indexing tools available for this kind of thing, I have my...
1
1292
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 standpoint to declaring all my string constants up-front as opposed to declaring them in-line? For example: public class ProjectConsts {
4
5349
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 the Identifier. The logical way would be to read the record once and put it in an STL container such as vector and then use lower_bound to search for a given identifier. But for some strange reason i'm asked to not use a container but instead...
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4066
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.