Get a list from config.ini file - python

In my config file I have something like that :
[Section_1]
List=Column1,Column2,Column3,Column4
Now, I would like to process it in my main file as normal lists :
config = configparser.ConfigParser()
config.read("configTab.ini")
for index in range(len(List)):
sql=sql.replace(List[index],"replace("+List[index]+","'hidden'")")
Now when I read from configuration file "List" is a normal String.
What is the best approach to to it?
If I put a normal list variable in my main code it this way:
List=['Column1','Column2','Column3','Column4']
Then it works fine, but I would like to get that from my configure file,
Thanks

Use str.split:
List = List.split(',')
string = 'a, b, c'
print(string.split(','))
>> ['a', 'b', 'c']

The answer by #DeepSpace is not entirely correct. The leading whitespace around 'b' and 'c' is included in the output if one executes this line as written (e.g. 'b' is actually ' b').
To avoid leading and trailing whitespace, try:
string = 'a, b, c'
print([i.strip() for i in string.split(',')])
>> ['a', 'b', 'c']

Use Regular expression to remove extra space and split with commas
re.py
pattern = re.compile("^\s+|\s*,\s*|\s+$")
str_list = 'a, b, c'
cis_list = pattern.split(str_list)
>> ['a', 'b', 'c']

Related

How to convert a string to a list if the string has wild characters for a group of characters like [] or {}, ()

I have a string of this sort
s = 'a,s,[c,f],[f,t]'
I want to convert this to a list
S = ['a','s',['c','f'],['f','t']]
I tried using strip()
d = s.strip('][').split(',')
But it is not giving me the desired output:
output = ['a', 's', '[c', 'f]', '[f', 't']
You could use ast.literal_eval(), having first enclosed each element in quotes:
>>> qs = re.sub(r'(\w+)', r'"\1"', s) # add quotes
>>> ast.literal_eval('[' + qs + ']') # enclose in brackets & safely eval
['a', 's', ['c', 'f'], ['f', 't']]
You may need to tweak the regex if your elements can contain non-word characters.
This only works if your input string follows Python expression syntax or is sufficiently close to be mechanically converted to Python syntax (as we did above by adding quotes and brackets). If this assumption does not hold, you might need to look into using a parsing library. (You could also hand-code a recursive descent parser, but that'll probably be more work to do correctly than just using a parsing library.)
Alternative to ast.literal_eval you can use the json package with more or less the same restrictions of NPE's answer:
import re
import json
qs = re.sub(r'(\w+)', r'"\1"', s) # add quotes
ls = json.loads('[' + qs + ']')
print(ls)
# ['a', 's', ['c', 'f'], ['f', 't']]

Replace multiple symbols using replace()

How can I replace multiple symbols with the method replace()? Is it possible to do that with just one replace()? Or is there any better ways?
The symbols can look like this for example -,+,/,',.,&.
You can use re.sub and put the characters in a character class:
import re
re.sub('[-+/\'.&]', replace_with, input)
You may do it using str.join with generator expression (without importing any library) as:
>>> symbols = '/-+*'
>>> replacewith = '.'
>>> my_text = '3 / 2 - 4 + 6 * 9' # input string
# replace char in string if symbol v
>>> ''.join(replacewith if c in symbols else c for c in my_text)
'3 . 2 . 4 . 6 . 9' # Output string with symbols replaced
# '7' -> 'A', '8' -> 'B'
print('asdf7gh8jk'.replace('7', 'A').replace('8', 'B'))
You can only do one symbol replace, what you could do is create the old strings and new strings list and loop them:
string = 'abc'
old = ['a', 'b', 'c']
new = ['A', 'B', 'C']
for o, n in zip(old, new):
string = string.replace(o, n)
print string
>>> 'ABC'

Pythonic way to join list and wrap result with same separator

I need to convert list ['a', 'b', 'c'] to string '/a/b/c/'
This example does not look like a good practice:
'/' + '/'.join(['a','b','c']) + '/'
>>> '/a/b/c/'
EDIT
#TomDalton asked a very good question:
What do you want an empty list to result in? '', '/', or '//'?
I want single slash '/' in case of empty list.
How about this:
'/' + ''.join([i + '/' for i in ['a', 'b', 'c'])
?
The solution you have given is fine. You could using string formatting to make it look a little nicer:
'/{0}/'.format('/'.join(['a', 'b'. 'c'])
Or in the future in 3.6 with Literal String Interpolation:
f"/{format('/'.join(['a', 'b'. 'c'])}/"
You could simply add two empty strings to the list:
>>> "/".join(['', 'a', 'b', 'c', ''])
'/a/b/c/'

How to save the results from nltk function "most_informative_features" to a txt file in Python

Sorry if this is a noobie question! I am carrying out sentiment analysis on python using nltk. It has a function which returns the most informative features but whenever i try and save the results to a text file, i get the following error 'TypeError: must be str, not list'. the code i am using is as follows
classifier.most_informative_features(100)
str(information)
saveFile = open('informationFile.txt', 'w')
saveFile.write(information)
saveFile.close()
any ideas what i am doing wrong?
You need to assign the conversion from list to string to something, or do in place...
saveFile.write(''.join(information))
Applying str to a variable generates a value, but doesn't change the variable (unless you assign it)
>>> bar
['a', 'b', 'c']
>>> str(bar)
"['a', 'b', 'c']"
>>> bar
['a', 'b', 'c']
>>> ', '.join(bar)
'a, b, c'
>>> bar
['a', 'b', 'c']
>>> bar = ', '.join(bar)
>>> bar
'a, b, c'

Split string based on a regular expression

I have the output of a command in tabular form. I'm parsing this output from a result file and storing it in a string. Each element in one row is separated by one or more whitespace characters, thus I'm using regular expressions to match 1 or more spaces and split it. However, a space is being inserted between every element:
>>> str1="a b c d" # spaces are irregular
>>> str1
'a b c d'
>>> str2=re.split("( )+", str1)
>>> str2
['a', ' ', 'b', ' ', 'c', ' ', 'd'] # 1 space element between!!!
Is there a better way to do this?
After each split str2 is appended to a list.
By using (,), you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "a b c d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']
However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.
>>> str1.split()
['a', 'b', 'c', 'd']
If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):
>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']
or you can find all non-whitespace characters
>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']
The str.split method will automatically remove all white space between items:
>>> str1 = "a b c d"
>>> str1.split()
['a', 'b', 'c', 'd']
Docs are here: http://docs.python.org/library/stdtypes.html#str.split
When you use re.split and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.
Its very simple actually. Try this:
str1="a b c d"
splitStr1 = str1.split()
print splitStr1

Categories

Resources