在适当的位置将拆分的单词和标点符号与标点符号连接起来 [英] Join split words and punctuation with punctuation in the right place

查看:88
本文介绍了在适当的位置将拆分的单词和标点符号与标点符号连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在将字符串拆分为单词和标点符号后尝试使用join(),但是它将字符串与单词和标点符号之间的空格连接在一起.

So I tried using join() after splitting a string into words and punctuation but it joins the string with a space in between the word and punctuation.

b = ['Hello', ',', 'who', 'are', 'you', '?']
c = " ".join(b)

b = ['Hello', ',', 'who', 'are', 'you', '?']
c = " ".join(b)

但是返回:
c = 'Hello , who are you ?'

But that returns:
c = 'Hello , who are you ?'

我想要:
c = 'Hello, who are you?'

推荐答案

您可以先加入标点符号:

You could join on the punctuation first:

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生成器产生的字符串带有以下已加入的标点符号:

The join_punctuation generator yields strings with any following punctuation already joined on:

>>> b = ['Hello', ',', 'who', 'are', 'you', '?']
>>> list(join_punctuation(b))
['Hello,', 'who', 'are', 'you?']
>>> ' '.join(join_punctuation(b))
'Hello, who are you?'

这篇关于在适当的位置将拆分的单词和标点符号与标点符号连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆