我尝试使用 split()
函数将字符串分割成单词和标点符号,并在此之后使用 join()
函数,但是它会用一个空格将单词和标点符号连接起来。
b = ['Hello', ',', 'who', 'are', 'you', '?']
c = "".join(b)
但这样返回的结果为:
c = 'Hello , who are you ?'
而我希望得到的结果是:
c = 'Hello, who are you?'
我尝试使用 split()
函数将字符串分割成单词和标点符号,并在此之后使用 join()
函数,但是它会用一个空格将单词和标点符号连接起来。
b = ['Hello', ',', 'who', 'are', 'you', '?']
c = "".join(b)
但这样返回的结果为:
c = 'Hello , who are you ?'
而我希望得到的结果是:
c = 'Hello, who are you?'
def join_punctuation(seq, characters='.,;?!'):
characters = set(characters)
seq = iter(seq)
current = next(seq)
for nxt in seq:
if nxt in characters:
current += nxt
else:
yield current
current = nxt
yield current
c = ' '.join(join_punctuation(b))
join_punctuation
生成器会产生已连接任何后续标点符号的字符串:>>> b = ['Hello', ',', 'who', 'are', 'you', '?']
>>> list(join_punctuation(b))
['Hello,', 'who', 'are', 'you?']
>>> ' '.join(join_punctuation(b))
'Hello, who are you?'
可能类似于:
>>> from string import punctuation
>>> punc = set(punctuation) # or whatever special chars you want
>>> b = ['Hello', ',', 'who', 'are', 'you', '?']
>>> ''.join(w if set(w) <= punc else ' '+w for w in b).lstrip()
'Hello, who are you?'
b
中不完全由标点符号组成的单词前添加一个空格。在得到结果之后再做这件事情,虽然不完美但是可行...
c = re.sub(r' ([^A-Za-z0-9])', r'\1', c)
输出:
c = 'Hello , who are you ?'
>>> c = re.sub(r' ([^A-Za-z0-9])', r'\1', c)
>>> c
'Hello, who are you?'
>>>
re.sub(r' (?=\W)', '', c)
更简单。 - georg基于Martijn Pieters♦的答案,我对那些标点符号也可以出现在单词开头的语言进行了一些概括。
from string import punctuation
def join_punctuation(
seq,
characters_after=punctuation,
characters_before="¡¿"
):
characters_after = set(characters_after)
characters_before = set(characters_before)
seq = iter(seq)
current = next(seq)
for nxt in seq:
if current in characters_before:
current += nxt
elif nxt in characters_after:
current += nxt
else:
yield current
current = nxt
yield current
它的工作方式是相同的:
>>> b = ["Hola", ",", "¿", "Qué", "tal", "?"]
>>> list(join_punctuation(b))
['Hola,', '¿Qué', 'tal?']
>>> " ".join(join_punctuation(b))
'Hola, ¿Qué tal?'
怎么样?
c = " ".join(b).replace(" ,", ",")
?
执行相同的操作,而且可能会有更多类型的标点符号。 - Martijn Pieters
'Hello,whoareyou?'
。 - Martijn Pieters