[英]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',','
我需要拆分的标点符号
times,
,是'times',','
or another example if I have Why?!?
还是另一个例子,如果我有
Why?!?
I would need it to be 'Why','?!?'
我需要它是
'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! 我知道它根本不是python语言! but that's what I want it to do.
但这就是我想要的。
You can use finditer
even if the string is more complex. 即使字符串更复杂,也可以使用
finditer
。
>>> 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.