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
6 1506
If names always start with Name: in your file and is separated by a white space then this should do it - file = open('name.txt', 'r')
-
for line in file:
-
if line.startswith('Name:'):
-
name = line.split()[1]
-
print name
-
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
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: - def run_script():
-
try:
-
from param import ResponseNotOK, Units, Dialog, Warning, dim
-
from macrolib.ExceptWarn import formatExceptionInfo
-
from macrolib.PolarPt import polar_pt_plan
-
from point import Point
-
from job import JobName
-
from cons_line import ConsLine
-
import os
-
import string
-
Units("feet")
-
-
#####################################
-
def gridAdd(pt, dir, cons_color="Cyan"):
-
# construction line begin
-
cl2 = ConsLine()
-
cl2.pt1 = pt
-
cl2.angle = dir
-
cl2.pen = cons_color
-
cl2.add()
-
# construction line end
-
####################################
-
-
## Dialog Box ######################
-
dlg1 = Dialog("Building Grid Lines in Plan")
-
dlg1.group_title("Import Grid Line File")
-
dlg1.file('import_file', os.path.join(os.getcwd(), "jobs", JobName(), "macro", "TownCtrGrids.txt"), "Enter file name or browse ")
-
dlg1.menu('cons_color', ("Blue", "Green", "Yellow", "Magenta", "Red", "White", "Cyan"), "Blue", "Construction line color")
-
-
try:
-
dlg1.done()
-
except ResponseNotOK:
-
raise
-
-
# Import grid line file
-
try:
-
f = open(dlg1.import_file, "r")
-
except IOError, e:
-
# unable to open file
-
Warning("Unable to open file: %s" % (e))
-
-
for item in f:
-
if "origin" in string.lower(item):
-
ptx, pty = item.split(':')[1].split(",")
-
gridWP = Point(dim(ptx.strip()), dim(pty.strip()), 0.0)
-
elif "direction" in string.lower(item):
-
gridOffset = 0.0
-
gridDir = dim(item.split(':')[1].strip())
-
gridAdd(gridWP, gridDir, dlg1.cons_color)
-
else:
-
if dim(item.strip()):
-
gridOffset = gridOffset + dim(item.strip())
-
gridAdd(polar_pt_plan(gridWP, gridOffset, gridDir + 90.0), gridDir, dlg1.cons_color)
-
f.close()
-
except:
-
Warning(formatExceptionInfo())
-
## END run_script() #########################
-
if __name__ == '__main__':
-
try:
-
run_script()
-
finally:
-
del run_script
Thanks to this list for the pointers received!
If names always start with Name: in your file and is separated by a white space then this should do it - file = open('name.txt', 'r')
-
for line in file:
-
if line.startswith('Name:'):
-
name = line.split()[1]
-
print name
-
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
This will do it... - file = open('name.txt', 'r')
-
for line in file:
-
if line.find('Name:') >= 0:
-
name = line.split()[-1]
-
print name
-
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
This will do it... - file = open('name.txt', 'r')
-
for line in file:
-
if line.find('Name:') >= 0:
-
name = line.split()[-1]
-
print name
-
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
bvdet 2,851
Recognized Expert Moderator Specialist Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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.
|
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...
|
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
|
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()
| |
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().
|
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...
|
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
{
|
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...
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |