0

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.

4

4 回答 4

3

finditer即使字符串更复杂,您也可以使用。

    >>> r = re.compile(r"(\w+)(["+string.punctuation+"]*)")
    >>> s = 'Why?!?Why?*Why'
    >>> [x.groups() for x in r.finditer(s)]
    [('Why', '?!?'), ('Why', '?*'), ('Why', '')]
    >>> 
于 2013-07-16T16:45:06.440 回答
1

您可以使用正则表达式,例如:

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]: 
于 2013-07-16T16:39:06.820 回答
0

没有正则表达式的生成器解决方案:

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))
于 2013-07-16T17:48:36.210 回答
0

像这样的东西?(假设 punct 总是在结尾)

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)
于 2013-07-16T16:48:13.750 回答