473,549 Members | 2,247 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Split text file into words

The standard split() can use only one delimiter. To split a text file
into words you need multiple delimiters like blank, punctuation, math
signs (+-*/), parenteses and so on.

I didn't succeeded in using re.split()...
Jul 18 '05 #1
4 18286
On Tuesday 08 March 2005 14:43, qwweeeit wrote:
The standard split() can use only one delimiter. To split a text file
into words you need multiple delimiters like blank, punctuation, math
signs (+-*/), parenteses and so on.

I didn't succeeded in using re.split()...


Then try again... ;) No, seriously, re.split() can do what you want. Just
think about what are word delimiters.

Say, you want to split on all whitespace, and ",", ".", and "?", then you'd
use something like:

heiko@heiko ~ $ python
Python 2.3.5 (#1, Feb 27 2005, 22:40:59)
[GCC 3.4.3 20050110 (Gentoo Linux 3.4.3.20050110, ssp-3.4.3.20050110-0,
pie-8.7 on linux2
Type "help", "copyright" , "credits" or "license" for more information.
import re
teststr = "Hello qwweeeit, how are you? I am fine, today, actually."
re.split(r"[\s\.,\?]+",teststr)

['Hello', 'qwweeeit', 'how', 'are', 'you', 'I', 'am', 'fine', 'today',
'actually', '']

Extending with other word separators shouldn't be hard... Just have a look at

http://docs.python.org/lib/re-syntax.html

HTH!

--
--- Heiko.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQBCLa5Yf0b pgh6uVAMRAh7RAJ 9LY1P1lLJmMz6v8 EPlGU46KGsPDwCc DxFb
jPZAoMBmLTkMlii FBP6s8bg=
=7kGS
-----END PGP SIGNATURE-----

Jul 18 '05 #2
qwweeeit wrote:
The standard split() can use only one delimiter. To split a text file
into words you need multiple delimiters like blank, punctuation, math
signs (+-*/), parenteses and so on.

I didn't succeeded in using re.split()...


Would you care to elaborate on how you tried to use re.split and failed? We
aren't mind readers here. An example of your non-working code along with
the expected result and the actual result would be useful.

This is the first example given in the documentation for re.split:
re.split('\W+', 'Words, words, words.')

['Words', 'words', 'words', '']

Does it do what you want? If not what do you want?
Jul 18 '05 #3
I thank you for your help.
I already used re.split successfully but in this case...
I didn't explain more deeply because I don't want someone else do my
homework.

I want to implement a variable & commands cross reference tool.
For this goal I must clean the python source from any comment and
manifest string.
On the cleaned source file I must isolate all the words (keeping the
words connected by '.')

My wrong code (don't consider the line ref. in traceback ... it's an
extract!):

import re

# input text file w/o strings & comments

f=open('file.tx t')
lInput=f.readli nes()
f.close()

fOut=open('word s.txt','w')

for i in lInput:
.. ll=re.split(r"[\s,{}[]()+=-/*]",i)
.. fOut.write(' '.join(ll)+'\n' )

fOut.close()

Traceback (most recent call last):
File "./GetWords.py", line 70, in ?
ll=re.split(r"[\s,{}[]()+=-/*]",i)
File "/usr/lib/python2.3/sre.py", line 156, in split
return _compile(patter n, 0).split(string , maxsplit)
RuntimeError: maximum recursion limit exceeded
.... and if I use:
ll=re.split(r"\ s,{}[]()+=-/*",i)

Traceback (most recent call last):
File "./GetWords.py", line 70, in ?
ll=re.split(r"\ s,{}[]()+=-/*",i)
File "/usr/lib/python2.3/sre.py", line 156, in split
return _compile(patter n, 0).split(string , maxsplit)
File "/usr/lib/python2.3/sre.py", line 230, in _compile
raise error, v # invalid expression
sre_constants.e rror: bad character range

I taught it was my mistake in the use of re.split...

I am using:
Python 2.3.4 (#2, Aug 19 2004, 15:49:40)
[GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2
Jul 18 '05 #4
qwweeeit wrote:
ll=re.split(r"[\s,{}[]()+=-/*]",i)


The stack overflow comes because the ()+ tried to match an empty string as
many times as possible.

This regular expression contains a character set '\s,{}[' followed by the
expression '()+=-/*]'. You can see that the parentheses aren't part of a
character set if you reverse their order which gives you an error when the
expression is compiled instead of failing when trying to match:
ll=re.split(r"[\s,{}[])(+=-/*]",i)
Traceback (most recent call last):
File "<pyshell#1 0>", line 1, in -toplevel-
ll=re.split(r"[\s,{}[])(+=-/*]",i)
File "C:\Python24\Li b\sre.py", line 157, in split
return _compile(patter n, 0).split(string , maxsplit)
File "C:\Python24\Li b\sre.py", line 227, in _compile
raise error, v # invalid expression
error: unbalanced parenthesis


I suspect you actually meant the character set to include the other
punctuation characters in which case you need to escape the closing square
bracket or make it the first character:

Try:

ll=re.split(r"[\s,{}[\]()+=-/*]",i)

or:

ll=re.split(r"[]\s,{}[()+=-/*]",i)

instead.
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2645
by: Jocknerd | last post by:
I'm a Python newbie and I'm having trouble with Regular Expressions when reading in a text file. Here is a sample layout of the input file: 09/04/2004 Virginia 44 Temple 14 09/04/2004 LSU 22 Oregon State 21 09/09/2004 Troy State 24 Missouri 14 As you can...
6
4263
by: Ruben | last post by:
Hello. I am trying to read a small text file using the readline statement. I can only read the first 2 records from the file. It stops at the blank lines or at lines with only spaces. I have a while statement checking for an empty string "" which I understand represents an EOF in Python. The text file has some blank lines with spaces and...
5
1414
by: Amjad Farran | last post by:
What is the easiest way to display in a table, a delimited text data saved in a text file? I need an idea so that I can research it! Amjad
2
1816
by: ownowl | last post by:
Hello beginer under python, I have a problem to get lines in a text file. lines have inside the \n (x0A) char, and le readline method split the line at this char too (not only at x0Dx0A). for resume, I want to split a file to lines with only those chars : x0Dx0A A idea ? thank's Olivier
2
1074
by: damezumari | last post by:
I am running a vbnet web application http://localhost/passwords/passwords.aspx on windows 2000 where a text file is read into a temporary datatable called Table1. Here is the problematic part of my code: Dim sr As StreamReader = New StreamReader(Filename) Dim line As String Do
3
9159
by: eyalhz | last post by:
I everyone- I need help with this code of mine, it has to be fixed a little...( IN VB NET 2005) I have some text files,and every text file has two words (in different languages) and they are seperated by (=) equal mark , I want at form load- to load all the text file into a listbox (without an extension),and with click on one of the files...
1
1698
by: Alan T | last post by:
I have a text file would like to read the word by word.
4
8429
by: bigbagy | last post by:
Notes The programs will be compiled and tested on the machine which runs the Linux operating system. V3.4 of the GNU C/C++ compiler (gcc ,g++) must be used. A significant amount coding is needed for this assignment. 1.Counting Words in C++ Problem: Write an elegant C++ program to count the number of times each word occurs in a...
3
4272
by: Jonas Peter | last post by:
Hi guys, I have got a question that I would love for you guys to give me an idea on how to get started with. First of all, I'm using Windows 7 and Python 2.7 I've got a text file and im trying to read the text from that file and then check every word with 40 words around that word, to make sure the word in question has not been repeated...
0
7548
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...
0
7472
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7743
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7986
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...
1
7504
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...
1
5391
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3499
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1083
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
786
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...

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.