473,326 Members | 1,972 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,326 software developers and data experts.

How to use brackets in Python?

Thebuilderofdoom
Expand|Select|Wrap|Line Numbers
  1. nubr1 = 0
  2. s = open("C:/DsE2/T1.txt").read()
  3.  
  4. while nubr1 <=5:
  5.     lib1l[nubr1] = open("C:/DsE2/lib001.txt").readlines()[nubr1]
  6.     lib2l[nubr1] = open("C:/DsE2/lib002.txt").readlines()[nubr1]
  7.     s = s.replace( lib1l[nubr1] ,lib2l[nubr1] )
  8.     nubr1 = nubr1 + 1
  9.  
  10.  
  11. f = open("C:/DsE2/T1.txt", 'w')
  12. f.write(s)
  13. f.close()
is this how you use brackets?

---How this program works---
reads C:/DsE2/lib002.txt,C:/DsE2/lib001.txt,C:/DsE2/T1.txt
replace words in C:/DsE2/T1.txt with line one in C:/DsE2/lib001.txt to line one in
C:/DsE2/lib002.txt then replaces words in C:/DsE2/T1.txt with line two in C:/DsE2/lib001.txt to line two in C:/DsE2/lib002.txt and soo on...
-------------------------------------------
Mar 15 '10 #1

✓ answered by Glenton

Expand|Select|Wrap|Line Numbers
  1. #First create dictionary for replacements:
  2. myD={}
  3. L1=open("lib001")
  4. L2=open("lib002")
  5. for l1,l2 in zip(L1,L2):
  6.     myD[l1.strip()]=l2.strip()
  7. L1.close()
  8. L2.close()
  9. print myD
Gives this:
{'how': ':)', 'you': 'o', 'hi': 'hello', 'hello': ':D', 'are': 'hi'}

Expand|Select|Wrap|Line Numbers
  1. #Next get the text you want to replace
  2. T1=open("T1.txt","r")  #read only mode
  3. mytxt=T1.readline().strip()
  4. T1.close()
  5. print mytxt
Gives this:
hi how are you?how's it going?hello?

Expand|Select|Wrap|Line Numbers
  1. #Thirdly, do replaces on the text
  2. for t1 in myD:
  3.     mytxt=mytxt.replace(t1,myD[t1])
  4. print mytxt
Gives this:
:D :) hi o?:)'s it going?:D?
(NOTE: this may not work properly because it might substitute hi for hello, and then hello for :D - this can be fixed by using two lists instead of a dictionary so that you can control the order of substitution)

Expand|Select|Wrap|Line Numbers
  1. #Finally, write the new text to file
  2. T2=open("T2.txt","w")  #write mode
  3. T2.write(mytxt)
  4. T2.close()
This creates a file called T2.txt with :D :) hi o?:)'s it going?:D? as the content. Of course, you could just use T1.txt if you wanted to over-write the original T1.txt file, but during the development phase that's probably not the best plan!

15 13829
bvdet
2,851 Expert Mod 2GB
Brackets are tokens used as delimiters for lists, index of sequence types, and the slicing operator. I don't think your method will achieve the results you want. file method read() reads the entire file as one string. You could iterate on the file object (for line in fileObj:) and use file method next() on the other two files, so you could do whatever you need to line 1 of each file, then line 2 of each file, and so on.
Mar 15 '10 #2
i don't know half of what you saying? please explain in a more simpler
Mar 15 '10 #3
bvdet
2,851 Expert Mod 2GB
A list:
Expand|Select|Wrap|Line Numbers
  1. [1,2,3,4,]
An element of a list and string accessed by index:
Expand|Select|Wrap|Line Numbers
  1. >>> [1,2,3,4][1]
  2. 2
  3. >>> '12345'[-1]
  4. '5'
  5. >>> 
A slice of a sequence type (list, tuple, string)
Expand|Select|Wrap|Line Numbers
  1. >>> [1,2,3,4][1]
  2. 2
  3. >>> '12345'[-1]
  4. '5'
  5. >>> [1,2,3,4][1:3]
  6. [2, 3]
  7. >>> '12345'[::-1]
  8. '54321'
  9. >>> '12345'[1:3]
  10. '23'
  11. >>> 
Here's an example of reading two text files at the same time:
Expand|Select|Wrap|Line Numbers
  1. f1 = open("file1.txt")
  2. f2 = open("file2.txt")
  3. for line in f1:
  4.     print line.strip()
  5.     try:
  6.         line2 = f2.next()
  7.         print line2.strip()
  8.     except StopIteration, e:
  9.         print "Reached end of file 2"
  10.         break
  11.  
  12. f1.close()
  13. f2.close()
Of course, iteration will cease when the end of file 1 is reached, or the try/except block will catch the StopIteration exception raised by the next() method. Iteration on the file object in a for loop uses the next() method behind the scenes and catches the StopIteration exception.
Mar 15 '10 #4
um... how come this would work then?

Expand|Select|Wrap|Line Numbers
  1. nubr1 = 0
  2. s = open("C:/DsE2/T1.txt").read()
  3. f = open("C:/DsE2/T1.txt", 'w')
  4.  
  5. while 1==1:
  6. if nubr1 <=5:
  7. lib1l+`nubr1` = open("C:/DsE2/lib001.txt").readlines()[nubr1]
  8. lib2l+`nubr1` = open("C:/DsE2/lib002.txt").readlines()[nubr1]
  9. s = s.replace( lib1l+`nubr1` ,`lib2l+nubr1` )
  10. nubr1 = nubr1 + 1
  11. f.write(s)
  12. else:
  13.  
  14. f.close()
Mar 15 '10 #5
bvdet
2,851 Expert Mod 2GB
You have no indentation in your code. How will you know what to replace in "T1.txt" if you read the entire file into a string? You cannot make an assignment like this:
Expand|Select|Wrap|Line Numbers
  1. lib1l+`nubr1` = ........
There is no need in reading lib001.txt and lib002.txt over and over again. Read each file once outside the while loop.
Mar 15 '10 #6
so how you read once? then replace all?
Mar 15 '10 #7
bvdet
2,851 Expert Mod 2GB
I am unsure what you are trying to accomplish. Could you be more specific, post a sample from the files and what the results are supposed to look like?
Mar 15 '10 #8
ok here is what i am trying.. to do
Example:
lib001
Expand|Select|Wrap|Line Numbers
  1. hello
  2. hi
  3. how
  4. are
  5. you
  6.  
lib002
Expand|Select|Wrap|Line Numbers
  1. :D
  2. hello
  3. :)
  4. hi
  5. o
  6.  
Target File:Before
Expand|Select|Wrap|Line Numbers
  1. hi how are you?how's it going?hello?
  2.  
Target File:After
Expand|Select|Wrap|Line Numbers
  1. hello :) o hi?hello's it going?:D
  2.  
--Example--
get all lines in lib001 replaces it it with the lines in lib002 in the target file
Mar 15 '10 #9
bvdet
2,851 Expert Mod 2GB
Now I understand what you are trying to do. Read file1 into a string as you did. Open the two data files and use readlines() to create two lists. Remember that the list elements will have newline characters that need to be stripped. Assuming the string is name s1 and the lists are s2List and s3List:
Expand|Select|Wrap|Line Numbers
  1. for i, word in enumerate(s2List):
  2.     s1 = s1.replace(word.strip(), s3List[i].strip())
Mar 16 '10 #10
Glenton
391 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. #First create dictionary for replacements:
  2. myD={}
  3. L1=open("lib001")
  4. L2=open("lib002")
  5. for l1,l2 in zip(L1,L2):
  6.     myD[l1.strip()]=l2.strip()
  7. L1.close()
  8. L2.close()
  9. print myD
Gives this:
{'how': ':)', 'you': 'o', 'hi': 'hello', 'hello': ':D', 'are': 'hi'}

Expand|Select|Wrap|Line Numbers
  1. #Next get the text you want to replace
  2. T1=open("T1.txt","r")  #read only mode
  3. mytxt=T1.readline().strip()
  4. T1.close()
  5. print mytxt
Gives this:
hi how are you?how's it going?hello?

Expand|Select|Wrap|Line Numbers
  1. #Thirdly, do replaces on the text
  2. for t1 in myD:
  3.     mytxt=mytxt.replace(t1,myD[t1])
  4. print mytxt
Gives this:
:D :) hi o?:)'s it going?:D?
(NOTE: this may not work properly because it might substitute hi for hello, and then hello for :D - this can be fixed by using two lists instead of a dictionary so that you can control the order of substitution)

Expand|Select|Wrap|Line Numbers
  1. #Finally, write the new text to file
  2. T2=open("T2.txt","w")  #write mode
  3. T2.write(mytxt)
  4. T2.close()
This creates a file called T2.txt with :D :) hi o?:)'s it going?:D? as the content. Of course, you could just use T1.txt if you wanted to over-write the original T1.txt file, but during the development phase that's probably not the best plan!
Mar 16 '10 #11
um.... it breaks after around 100 lines in the lib001 and lib002
Mar 17 '10 #12
Glenton
391 Expert 256MB
It's possible that it would run out of memory at some point, but not after 100 lines. So they must have the same number of lines. And some characters might cause a problem, I guess.

"it breaks" is, I'm afraid, simply woefully inadequate. My program wasn't trying to solve it for you, but rather to show you a method for solving it yourself. If you'd like help debugging, please post the issue.
Mar 17 '10 #13
the lib001 and the lib002 both have 58112 words each(not together)
Error
<open file 'C:/DsE2/lib001.txt', mode 'r' at 0x010242F0>
<open file 'C:/DsE2/lib002.txt', mode 'r' at 0x010242F0>
and then when it put
L1=open("C:/DsE2/lib001.txt").read()
L2=open("C:/DsE2/lib002.txt").read()
it put rubbish into C:/DsE2/T2.txt
Mar 17 '10 #14
bvdet
2,851 Expert Mod 2GB
Did Python raise an exception? Why did you execute file method read() on L1 and L2? That was not in Glenton's example nor mine.
Mar 18 '10 #15
no and just to test stuff.. see if a different approach can fix it
Mar 18 '10 #16

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

Similar topics

21
by: deko | last post by:
Do I need to use curly brackets in PHP if .. else statements? other constructs? Does it matter? What are Best Practices? Why? thanks in advance... This seems to work WITHOUT curly brackets:...
3
by: Eric Ellsworth | last post by:
Hi all, Does anyone have any bright ideas for Access' tendency to add square brackets when it parses queries, then tell you that the query syntax is invalid. In my case, I'm trying to do a LEFT...
2
by: Zain Homer | last post by:
Someone please let me know if I'm sending this to the wrong email alias... I'm wondering why we can't use the glob module to glob with curly brackets like we can from the command line (at least...
17
by: Qiangning Hong | last post by:
I've got some strings to split. They are main words, but some words are inside a pair of brackets and should be considered as one unit. I prefer to use re.split, but haven't written a working one...
5
by: Stef Mientki | last post by:
If I call a parameterless function without brackets at the end, the function is not performed, but ... I don't get an error message ??? Is this normal behavior ? thanks, Stef Mientki
24
by: dmitrey | last post by:
Hi all, I looked to the PEPs & didn't find a proposition to remove brackets & commas for to make Python func call syntax caml- or tcl- like: instead of result = myfun(param1, myfun2(param5,...
4
by: Nunzio | last post by:
I am trying to build an email address in PHP code using v5.1.2. All works well until I try to surround the email address with angle brackets. Every method I try causes the email address to...
5
by: narutocanada | last post by:
hi what is the difference between the two kinds of brackets? I tried a few examples but I can't make out any real difference: lst = print lst print lst print lst lst = (10, 20, 30) print...
4
by: NevilleDNZ | last post by:
Below is a (flawed) one line RegEx that checks curly brackets (from awk/c/python input) are being matched. Is there a one liner for doing this in python? ThanX N ...
4
by: Keith Hughitt | last post by:
Hi all, I am using someone else's script which expects input in the form of: ./script.py <arg1arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
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: 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
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.