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 1492
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
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: - 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
Expert Mod 2GB 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)...
|
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...
|
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...
|
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...
|
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:
...
|
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...
|
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?...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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)...
|
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...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
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....
|
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
|
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...
|
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...
| |