简体   繁体   中英

Python split punctuation but still include it

This is the list of strings that I have:

 [
  ['It', 'was', 'the', 'besst', 'of', 'times,'], 
  ['it', 'was', 'teh', 'worst', 'of', 'times']
 ]

I need to split the punctuation in times, , to be 'times',','
or another example if I have Why?!? I would need it to be 'Why','?!?'

import string

def punctuation(string):

for word in string:
    if word contains (string.punctuation):
        word.split()

I know it isn't in python language at all! but that's what I want it to do.

You can use finditer even if the string is more complex.

    >>> r = re.compile(r"(\w+)(["+string.punctuation+"]*)")
    >>> s = 'Why?!?Why?*Why'
    >>> [x.groups() for x in r.finditer(s)]
    [('Why', '?!?'), ('Why', '?*'), ('Why', '')]
    >>> 

you can use regular expression, for example:

In [1]: import re

In [2]: re.findall(r'(\w+)(\W+)', 'times,')
Out[2]: [('times', ',')]

In [3]: re.findall(r'(\w+)(\W+)', 'why?!?')
Out[3]: [('why', '?!?')]

In [4]: 

Something like this? (Assumes punct is always at end)

def lcheck(word):
    for  i, letter in enumerate(word):
        if not word[i].isalpha():
            return [word[0:(i-1)],word[i:]]
    return [word]

value = 'times,'
print lcheck(value)

A generator solution without regex:

import string
from itertools import takewhile, dropwhile

def splitp(s):
    not_punc = lambda c: c in string.ascii_letters+"'"  # won't split "don't"
    for w in s:
        punc = ''.join(dropwhile(not_punc, w))
        if punc:
            yield ''.join(takewhile(not_punc, w))
            yield punc
        else:
            yield w

list(splitp(s))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM