I want to search for the existence of the word hi.
import re
word = 'hi?'
cleanString = re.sub('\W+',' ', word)
print(cleanString.lower())
GREETING_INPUTS = ("hello", 'hi', 'hii', "hey")
if cleanString.lower() in GREETING_INPUTS:
print('yes')
else:
print('no')
When word = 'hi', it prints yes. But for word = 'hi?', it prints no. Why is it so and please suggest any solution.
Replace this line:
cleanString = re.sub('\W+',' ', word)
With:
cleanString = re.sub('\W+','', word)
Because you're replacing all the matches of '\W+' with ' ', a space, so the string would be 'hi ', so then you need to replace it with empty string '' for it to work, the string would become 'hi'
I am creating some code that will replace spaces.
I want a double space to turn into a single space and a single space to become nothing.
Example:
string = "t e s t t e s t"
string = string.replace(' ', ' ').replace(' ', '')
print (string)
The output is "testest" because it replaces all the spaces.
How can I make the output "test test"?
Thanks
A regular expression approach is doubtless possible, but for a quick solution, first split on the double space, then rejoin on a single space after using a comprehension to remove the single spaces in each of the elements in the split:
>>> string = "t e s t t e s t"
>>> ' '.join(word.replace(' ', '') for word in string.split(' '))
'test test'
Just another idea:
>>> s = 't e s t t e s t'
>>> s.replace(' ', ' ').replace(' ', '').replace(' ', '')
'test test'
Seems to be faster:
>>> timeit(lambda: s.replace(' ', ' ').replace(' ', '').replace(' ', ''))
2.7822862677683133
>>> timeit(lambda: ' '.join(w.replace(' ','') for w in s.split(' ')))
7.702567737466012
And regex (at least this one) is shorter but a lot slower:
>>> timeit(lambda: re.sub(' ( ?)', r'\1', s))
37.2261058654488
I like this regex solution because you can easily read what's going on:
>>> import re
>>> string = "t e s t t e s t"
>>> re.sub(' {1,2}', lambda m: '' if m.group() == ' ' else ' ', string)
'test test'
We search for one or two spaces, and substitute one space with the empty string but two spaces with a single space.
How do you split everything between ""s in Python? Including the ""s itself?
For example, I want to split something like print "HELLO" to just ['print '] because I split everything in the quotes, including the quotes itself.
Other examples:
1) print "Hello", "World!" => ['print ', ', ']
2) if "one" == "one": print "one is one" => ['if ', ' == ', ': print ']
Any help is appreciated.
Use re.split():
In [3]: re.split('".*?"', 'print "HELLO"')
Out[3]: ['print ', '']
In [4]: re.split('".*?"', '"Goodbye", "Farewell", and "Amen"')
Out[4]: ['', ', ', ', and ', '']
Note the use of .*?, the non-greedy all-consuming pattern.
You can use the regex '"[^"]*"' for re.split:
Example:
txt='''\
print "HELLO"
print "Hello", "World!"
if "one" == "one": print "one is one"
'''
width=len(max(txt.splitlines(), key=len))
for line in txt.splitlines():
print '{:{width}}=>{}'.format(line, re.split(r'"[^"]*"', line), width=width+1)
Prints:
print "HELLO" =>['print ', '']
print "Hello", "World!" =>['print ', ', ', '']
if "one" == "one": print "one is one" =>['if ', ' == ', ': print ', '']
>>> import re
>>> text = 'print "Hello"'
>>> re.sub(r'".*?"', r'', text)
'print '
To help OP's single quote bug:
>>> import re
>>> text = 'print \'hello\''
>>> re.sub(r'\'.*?\'', r'', text)
'print '
I'm trying to make something that takes as input a list of strings, and returns a string that is the concatenation all those strings together. However, I'm trying to learn how to do it without the join method.
Here is the main bulk of my code:
def concat_list(p):
def main():
list = []
i = 1
print('Entering the empty string stops the input process.')
while True:
str_input = str(input('Enter string #' + str(i) + ': '))
if str_input == '': # empty string -> stop input process
if i > 1:
list.pop() # remove the last element ' ' from list
break
i = i + 1
list.append(str_input)
list.append(' ') # we want the user's input strings to be interspersed with ' '
# for instance: ['Python', ' ', 'is', 'so', ' ', 'cool']
print(list)
main()
The def concat_list is what someone recommended using in order to store/call the new concatenated text. Does anyone have any suggestions? I've hit a block. Using the join method would simplify things I know but I want to try to do it without.
join() is usually a better/more idiomatic approach, but you can also concatenate strings with + or +=:
>>> l = ['this', ' ', 'is', ' ', 'a', ' ', 'test']
>>> l
['this', ' ', 'is', ' ', 'a', ' ', 'test']
>>> def concat_list(l):
... s = ''
... for word in l:
... s += word
... return s
...
>>> concat_list(l)
'this is a test'
I need to split strings of data using each character from string.punctuation and string.whitespace as a separator.
Furthermore, I need for the separators to remain in the output list, in between the items they separated in the string.
For example,
"Now is the winter of our discontent"
should output:
['Now', ' ', 'is', ' ', 'the', ' ', 'winter', ' ', 'of', ' ', 'our', ' ', 'discontent']
I'm not sure how to do this without resorting to an orgy of nested loops, which is unacceptably slow. How can I do it?
A different non-regex approach from the others:
>>> import string
>>> from itertools import groupby
>>>
>>> special = set(string.punctuation + string.whitespace)
>>> s = "One two three tab\ttabandspace\t end"
>>>
>>> split_combined = [''.join(g) for k, g in groupby(s, lambda c: c in special)]
>>> split_combined
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t ', 'end']
>>> split_separated = [''.join(g) for k, g in groupby(s, lambda c: c if c in special else False)]
>>> split_separated
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t', ' ', 'end']
Could use dict.fromkeys and .get instead of the lambda, I guess.
[edit]
Some explanation:
groupby accepts two arguments, an iterable and an (optional) keyfunction. It loops through the iterable and groups them with the value of the keyfunction:
>>> groupby("sentence", lambda c: c in 'nt')
<itertools.groupby object at 0x9805af4>
>>> [(k, list(g)) for k,g in groupby("sentence", lambda c: c in 'nt')]
[(False, ['s', 'e']), (True, ['n', 't']), (False, ['e']), (True, ['n']), (False, ['c', 'e'])]
where terms with contiguous values of the keyfunction are grouped together. (This is a common source of bugs, actually -- people forget that they have to sort by the keyfunc first if they want to group terms which might not be sequential.)
As #JonClements guessed, what I had in mind was
>>> special = dict.fromkeys(string.punctuation + string.whitespace, True)
>>> s = "One two three tab\ttabandspace\t end"
>>> [''.join(g) for k,g in groupby(s, special.get)]
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t ', 'end']
for the case where we were combining the separators. .get returns None if the value isn't in the dict.
import re
import string
p = re.compile("[^{0}]+|[{0}]+".format(re.escape(
string.punctuation + string.whitespace)))
print p.findall("Now is the winter of our discontent")
I'm no big fan of using regexps for all problems, but I don't think you have much choice in this if you want it fast and short.
I'll explain the regexp since you're not familiar with it:
[...] means any of the characters inside the square brackets
[^...] means any of the characters not inside the square brackets
+ behind means one or more of the previous thing
x|y means to match either x or y
So the regexp matches 1 or more characters where either all must be punctuation and whitespace, or none must be. The findall method finds all non-overlapping matches of the pattern.
Try this:
import re
re.split('(['+re.escape(string.punctuation + string.whitespace)+']+)',"Now is the winter of our discontent")
Explanation from the Python documentation:
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.
Solution in linear (O(n)) time:
Let's say you have a string:
original = "a, b...c d"
First convert all separators to space:
splitters = string.punctuation + string.whitespace
trans = string.maketrans(splitters, ' ' * len(splitters))
s = original.translate(trans)
Now s == 'a b c d'. Now you can use itertools.groupby to alternate between spaces and non-spaces:
result = []
position = 0
for _, letters in itertools.groupby(s, lambda c: c == ' '):
letter_count = len(list(letters))
result.append(original[position:position + letter_count])
position += letter_count
Now result == ['a', ', ', 'b', '...', 'c', ' ', 'd'], which is what you need.
My take:
from string import whitespace, punctuation
import re
pattern = re.escape(whitespace + punctuation)
print re.split('([' + pattern + '])', 'now is the winter of')
Depending on the text you are dealing with, you may be able to simplify your concept of delimiters to "anything other than letters and numbers". If this will work, you can use the following regex solution:
re.findall(r'[a-zA-Z\d]+|[^a-zA-Z\d]', text)
This assumes that you want to split on each individual delimiter character even if they occur consecutively, so 'foo..bar' would become ['foo', '.', '.', 'bar']. If instead you expect ['foo', '..', 'bar'], use [a-zA-Z\d]+|[^a-zA-Z\d]+ (only difference is adding + at the very end).
from string import punctuation, whitespace
s = "..test. and stuff"
f = lambda s, c: s + ' ' + c + ' ' if c in punctuation else s + c
l = sum([reduce(f, word).split() for word in s.split()], [])
print l
For any arbitrary collection of separators:
def separate(myStr, seps):
answer = []
temp = []
for char in myStr:
if char in seps:
answer.append(''.join(temp))
answer.append(char)
temp = []
else:
temp.append(char)
answer.append(''.join(temp))
return answer
In [4]: print separate("Now is the winter of our discontent", set(' '))
['Now', ' ', 'is', ' ', 'the', ' ', 'winter', ' ', 'of', ' ', 'our', ' ', 'discontent']
In [5]: print separate("Now, really - it is the winter of our discontent", set(' ,-'))
['Now', ',', '', ' ', 'really', ' ', '', '-', '', ' ', 'it', ' ', 'is', ' ', 'the', ' ', 'winter', ' ', 'of', ' ', 'our', ' ', 'discontent']
Hope this helps
from itertools import chain, cycle, izip
s = "Now is the winter of our discontent"
words = s.split()
wordsWithWhitespace = list( chain.from_iterable( izip( words, cycle([" "]) ) ) )
# result : ['Now', ' ', 'is', ' ', 'the', ' ', 'winter', ' ', 'of', ' ', 'our', ' ', 'discontent', ' ']