473,554 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why isn't SPLIT splitting my strings

I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?

bests,

-rsr-

print "newstring =", str(result[i][0])
print "just split", str(result[i][0]).split('; ()[]"')
zd.append(str(r esult[i][0]).split('; ()[]"'))
result= (('Agricultural subsidies; Foreign aid',), ('Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals',),
('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',),
('Agricultural Subsidies',), ('Biodiversity' ,), ('Citizen Activism',),
('Community Gardens',), ('Cooperatives' ,), ('Dieting',), ('Agriculture,
Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',),
('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water,
Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal
Feed, Corn, Pesticides',), ('Aquaculture', ), ('Chemical Warfare',),
('Compost',), ('Debt',), ('Consumerism', ), ('Fear',), ('Pesticides, US,
Childhood Development, Birth Defects',), ('Corporate Reform,
Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming
(Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt,
Credit Cards',), ('Democracy',), ('Population, World',), ('Income',),
('Democracy, Corporate

partial results:

string a = Agricultural subsidies; Foreign aid
newstring = Agricultural subsidies; Foreign aid
just split ['Agricultural subsidies; Foreign aid']
newstring = Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals
just split ['Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals']
newstring = Antibiotics, Animals
just split ['Antibiotics, Animals']

Nov 19 '06 #1
8 2433
The regular string split does not take a _class_ of characters as the
separator, it only takes one separator. Your example suggests that you
expect that _any_ of the characters "; ()[]" could be a separator.
If you want to use a regular expression as a list of separators, then
you need to use the split function from the regular expression module
(re):
http://docs.python.org/lib/node46.html

Hope this helps,
Nick V.
ronrsr wrote:
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?

bests,

-rsr-

print "newstring =", str(result[i][0])
print "just split", str(result[i][0]).split('; ()[]"')
zd.append(str(r esult[i][0]).split('; ()[]"'))
result= (('Agricultural subsidies; Foreign aid',), ('Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals',),
('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',),
('Agricultural Subsidies',), ('Biodiversity' ,), ('Citizen Activism',),
('Community Gardens',), ('Cooperatives' ,), ('Dieting',), ('Agriculture,
Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',),
('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water,
Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal
Feed, Corn, Pesticides',), ('Aquaculture', ), ('Chemical Warfare',),
('Compost',), ('Debt',), ('Consumerism', ), ('Fear',), ('Pesticides, US,
Childhood Development, Birth Defects',), ('Corporate Reform,
Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming
(Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt,
Credit Cards',), ('Democracy',), ('Population, World',), ('Income',),
('Democracy, Corporate

partial results:

string a = Agricultural subsidies; Foreign aid
newstring = Agricultural subsidies; Foreign aid
just split ['Agricultural subsidies; Foreign aid']
newstring = Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals
just split ['Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals']
newstring = Antibiotics, Animals
just split ['Antibiotics, Animals']
Nov 19 '06 #2
"ronrsr" <ro****@gmail.c omwrote:
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?
I think your example boils down to:
>>help(str.spli t)
Help on method_descript or:

split(...)
S.split([sep [,maxsplit]]) -list of strings

Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.
>>s = 'Antibiotics, Animals'
s.split('; ()[]"')
['Antibiotics, Animals']

This is what I expect. The separator string '; ()[]"' does not occur
anywhere in the input string, so there is nowhere to split it.

If you want to split on multiple single characters, then either use
re.split and filter out the separators, or use string.translat e or
str.replace to replace all of the separators with the same character and
split on that. e.g.
>>def mysplit(s):
s = s.replace(' ', ';')
s = s.replace('(', ';')
s = s.replace(')', ';')
s = s.replace('[', ';')
s = s.replace(']', ';')
s = s.replace('"', ';')
return s.split(';')
>>mysplit(s)
['Antibiotics,', 'Animals']

which still looks a bit weird as output, but you never actually said what
output you wanted.
Nov 19 '06 #3
ronrsr wrote:
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be.
>>help(str.spli t)
split(...)
S.split([sep [,maxsplit]]) -list of strings

Return a list of the words in the string S, using sep as the
delimiter string.

note that it says *delimiter string*, not *list of characters that I
want it to split on*.

</F>

Nov 19 '06 #4
"ronrsr" <ro****@gmail.c omwrote in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?

bests,

-rsr-

print "newstring =", str(result[i][0])
print "just split", str(result[i][0]).split('; ()[]"')
zd.append(str(r esult[i][0]).split('; ()[]"'))
result= (('Agricultural subsidies; Foreign aid',), ('Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals',),
('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',),
('Agricultural Subsidies',), ('Biodiversity' ,), ('Citizen Activism',),
('Community Gardens',), ('Cooperatives' ,), ('Dieting',), ('Agriculture,
Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',),
('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water,
Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal
Feed, Corn, Pesticides',), ('Aquaculture', ), ('Chemical Warfare',),
('Compost',), ('Debt',), ('Consumerism', ), ('Fear',), ('Pesticides, US,
Childhood Development, Birth Defects',), ('Corporate Reform,
Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming
(Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt,
Credit Cards',), ('Democracy',), ('Population, World',), ('Income',),
('Democracy, Corporate

There are no ()'s or []'s in any of your tuple values, these are just
punctuation to show you the nested tuple structure of your db query results.
You say ';' is your keyword delimiter, so just split on ';'.

Also split('; ()[]') does not split on any one of the listed characters, but
only on the complete string '; ()[]', which occurs nowhere in your data.

-- Paul
# for each result in the tuple of tuples, split on ';', and then print the
results separated by " : " to show that we really did separate the results

for t in result:
print " : ".join(t[0].split(';'))

Gives:
Agricultural subsidies : Foreign aid
Agriculture : Sustainable Agriculture - Support : Organic Agriculture :
Pesticides, US,Childhood Development, Birth Defects : Toxic Chemicals
Antibiotics, Animals
Agricultural Subsidies, Global Trade
Agricultural Subsidies
Biodiversity
Citizen Activism
Community Gardens
Cooperatives
Dieting
Agriculture,Cot ton
Agriculture, Global Trade
Pesticides, Monsanto
Agriculture, Seed
Coffee, Hunger
Pollution, Water,Feedlots
Food Prices
Agriculture, Workers
AnimalFeed, Corn, Pesticides
Aquaculture
Chemical Warfare
Compost
Debt
Consumerism
Fear
Pesticides, US,Childhood Development, Birth Defects
Corporate Reform,Personho od (Dem. Book)
Corporate Reform, Personhood, Farming(Dem. Book)
Crime Rates, Legislation, Education
Debt,Credit Cards
Democracy
Population, World
Income
Nov 19 '06 #5
Meaning:

import re

newString= re.split('[; ()\[\]", result)

Nick Vatamaniuc wrote:
The regular string split does not take a _class_ of characters as the
separator, it only takes one separator. Your example suggests that you
expect that _any_ of the characters "; ()[]" could be a separator.
If you want to use a regular expression as a list of separators, then
you need to use the split function from the regular expression module
(re):
http://docs.python.org/lib/node46.html

Hope this helps,
Nick V.
ronrsr wrote:
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?

bests,

-rsr-

print "newstring =", str(result[i][0])
print "just split", str(result[i][0]).split('; ()[]"')
zd.append(str(r esult[i][0]).split('; ()[]"'))
result= (('Agricultural subsidies; Foreign aid',), ('Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals',),
('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',),
('Agricultural Subsidies',), ('Biodiversity' ,), ('Citizen Activism',),
('Community Gardens',), ('Cooperatives' ,), ('Dieting',), ('Agriculture,
Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',),
('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water,
Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal
Feed, Corn, Pesticides',), ('Aquaculture', ), ('Chemical Warfare',),
('Compost',), ('Debt',), ('Consumerism', ), ('Fear',), ('Pesticides, US,
Childhood Development, Birth Defects',), ('Corporate Reform,
Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming
(Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt,
Credit Cards',), ('Democracy',), ('Population, World',), ('Income',),
('Democracy, Corporate

partial results:

string a = Agricultural subsidies; Foreign aid
newstring = Agricultural subsidies; Foreign aid
just split ['Agricultural subsidies; Foreign aid']
newstring = Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals
just split ['Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals']
newstring = Antibiotics, Animals
just split ['Antibiotics, Animals']
Nov 19 '06 #6
Oops!

newString= re.split("[; ()\[\]", result)

John Henry wrote:
Meaning:

import re

newString= re.split('[; ()\[\]", result)

Nick Vatamaniuc wrote:
The regular string split does not take a _class_ of characters as the
separator, it only takes one separator. Your example suggests that you
expect that _any_ of the characters "; ()[]" could be a separator.
If you want to use a regular expression as a list of separators, then
you need to use the split function from the regular expression module
(re):
http://docs.python.org/lib/node46.html

Hope this helps,
Nick V.
ronrsr wrote:
I'm trying to break up the result tuple into keyword phrases. The
keyword phrases are separated by a ; -- the split function is not
working the way I believe it should be. Can anyone see what I"m doing
wrong?
>
bests,
>
-rsr-
>
>
>
print "newstring =", str(result[i][0])
print "just split", str(result[i][0]).split('; ()[]"')
zd.append(str(r esult[i][0]).split('; ()[]"'))
>
>
result= (('Agricultural subsidies; Foreign aid',), ('Agriculture;
Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US,
Childhood Development, Birth Defects; Toxic Chemicals',),
('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',),
('Agricultural Subsidies',), ('Biodiversity' ,), ('Citizen Activism',),
('Community Gardens',), ('Cooperatives' ,), ('Dieting',), ('Agriculture,
Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',),
('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water,
Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal
Feed, Corn, Pesticides',), ('Aquaculture', ), ('Chemical Warfare',),
('Compost',), ('Debt',), ('Consumerism', ), ('Fear',), ('Pesticides, US,
Childhood Development, Birth Defects',), ('Corporate Reform,
Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming
(Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt,
Credit Cards',), ('Democracy',), ('Population, World',), ('Income',),
('Democracy, Corporate
>
>
>
partial results:
>
string a = Agricultural subsidies; Foreign aid
newstring = Agricultural subsidies; Foreign aid
just split ['Agricultural subsidies; Foreign aid']
newstring = Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals
just split ['Agriculture; Sustainable Agriculture - Support; Organic
Agriculture; Pesticides, US, Childhood Development, Birth Defects;
Toxic Chemicals']
newstring = Antibiotics, Animals
just split ['Antibiotics, Animals']
Nov 19 '06 #7
John Henry wrote:
Oops!
for cases like this, writing

"[" + re.escape(chars et) + "]"

is usually a good way to avoid repeated oops:ing.
newString= re.split("[; ()\[\]", result)
>>newString= re.split("[; ()\[\]", result)
Traceback (most recent call last):
...
sre_constants.e rror: unexpected end of regular expression

</F>

Nov 19 '06 #8

Fredrik Lundh wrote:
John Henry wrote:
Oops!

for cases like this, writing

"[" + re.escape(chars et) + "]"
So, like this?

newString= re.split("[" + re.escape("; ()[]") + "]", result)
is usually a good way to avoid repeated oops:ing.
newString= re.split("[; ()\[\]", result)
>>newString= re.split("[; ()\[\]", result)
Traceback (most recent call last):
...
sre_constants.e rror: unexpected end of regular expression
Strange. It works for me. Oh, I know, it's missing a "]".

newString= re.split("[; ()\[\]]", result)
</F>
Nov 19 '06 #9

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

Similar topics

9
4335
by: Will McGugan | last post by:
Hi, I'm curious about the behaviour of the str.split() when applied to empty strings. "".split() returns an empty list, however.. "".split("*") returns a list containing one empty string. I would have expected the second example to have also returned an empty
5
57158
by: Vamsi | last post by:
Hi, I am trying a basic opearation of splitting a multiline value to an array of single lines(Actually making Address into AddressLine1, AddressLine2). I used Environment.NewLine in split, I could get only 1st line, but it is not returning 2nd line. here's code: string address = null; string ssep = Environment.NewLine; char sep =...
6
6362
by: Senthil | last post by:
Code ---------------------- string Line = "\"A\",\"B\",\"C\",\"D\""; string Line2 = Line.Replace("\",\"","\"\",\"\""); string CSVColumns = Line2.Split("\",\"".ToCharArray());
19
10900
by: David Logan | last post by:
We need an additional function in the String class. We need the ability to suppress empty fields, so that we can more effectively parse. Right now, multiple whitespace characters create multiple empty strings in the resulting string array.
5
5863
by: kurt sune | last post by:
The code: Dim aLine As String = "cat" & vbNewLine & "dog" & vbNewLine & "fox" & vbNewLine Dim csvColumns1 As String() = aLine.Split(vbNewLine, vbCr, vbLf) Dim csvColumns2 As String() = Microsoft.VisualBasic.Strings.Split(aLine, vbNewLine, -1, CompareMethod.Binary)
4
6029
by: Michele Petrazzo | last post by:
Hello ng, I don't understand why split (string split) doesn't work with the same method if I can't pass values or if I pass a whitespace value: >>> "".split() >>> "".split(" ") But into the doc I see:
4
4018
by: thiago_bagua | last post by:
Hi all, I have a csv file exported from excel. On cells where there was a comma in the text, it wraps the character with double quotes. For example: Column 1,"column two, and some more stuff",Column 3 In a c# dll, .NET framework 1.1, I'm reading the file using a streamreader then retrieving each line into a string using...
7
2917
by: John A Grandy | last post by:
Is string.Split() performant to a degree that there's no point in trying to write code to improve on its performance ?
14
1709
by: Stevo | last post by:
If you split a string into an array using the split method, it's not working the way I'd expect it to. That doesn't mean it's wrong of course, but would anyone else agree it's working somewhat illogically? Here's a test I just put together that splits on "&". The test strings are: "a&b" = (Correct!) I expect array length 2 and I get 2...
0
7611
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
7535
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...
1
7574
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...
0
7894
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...
0
6161
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...
0
3579
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3561
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1145
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
850
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.