在正确的位置使用标点符号连接拆分的单词和标点符号。

9

我尝试使用 split() 函数将字符串分割成单词和标点符号,并在此之后使用 join() 函数,但是它会用一个空格将单词和标点符号连接起来。

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

但这样返回的结果为:
c = 'Hello , who are you ?'

而我希望得到的结果是:
c = 'Hello, who are you?'


调用空字符串上的方法是否有效? - CBroe
@CBroe:不行,因为你会得到 'Hello,whoareyou?' - Martijn Pieters
3
好的,所以简单的连接不行,因为有不同“类型”的数据,包括词语和标点符号。所以我想需要一个自编方法,首先检查它是哪种类型,然后根据需要用空格或无空格将部分连接起来。 - CBroe
5个回答

8
你可以先按标点符号进行连接:
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?'

4
也许可以这样表述:

可能类似于:

>>> 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中不完全由标点符号组成的单词前添加一个空格。

3

在得到结果之后再做这件事情,虽然不完美但是可行...

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?'
>>> 

1
不错,除了 re.sub(r' (?=\W)', '', c) 更简单。 - georg

0

基于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?'

-1

怎么样?

c = " ".join(b).replace(" ,", ",")

2
你需要针对问号?执行相同的操作,而且可能会有更多类型的标点符号。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接