如何在每一句话中换行?

2024-09-30 16:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个长文本字符串中,如何为每5个句子添加一行新词,这是个难题

输入示例

text = 'The puppy is cute. Summer is great. Happy Friday. Sentence4. Sentence5. Sentence6. Sentence7.

期望输出:

The puppy is cute. Summer is great. Happy friday. Sentence4. Sentence5.
Sentence6. Sentence7.

有人能帮忙吗


Tags: the字符串文本cuteis句子happysummer
3条回答

下面是一个简单的函数,它在第五句的末尾添加了一个换行符

def new_line(sentence: str):
    # characters that mark the end of a sentence
    end_of_sentence_markers = ['.', '!', '?', '...']
    # after n sentences insert new_line
    n = 5

    # keeps track 
    count = 0
    # final string as list for efficiency
    final_str = []
    # split at space
    sentence_split = sentence.split(' ')

    # traverse the sentence split
    for word in sentence_split:
        # if end of sentence is present then increase count
        if word[-1] in end_of_sentence_markers:
            count += 1
        # if count is equal to n then add newline otherwise add space
        if count == n:
            final_str.append(word + '\n')
            count = 0
        else:
            final_str.append(word + ' ')


    # return the string version of the list
    return ''.join(final_str)

以下是修改后的版本:

def new_line_better(sentence: str, n: int):
    # final string as list for efficiency
    final_str = []
    # split at period and remove extra spaces
    sentence_split = list( map( lambda x : x.strip(),  sentence.split('.') ) )
    # pop off last space
    sentence_split.pop()
    
    # keeps track 
    count = 0
    # traverse the sentences
    for sentence in sentence_split:
        count += 1
        if count == n:
            count = 0
            final_str.append(sentence+'.\n')
        else:
            final_str.append(sentence+'. ')

    # return the string version of the list
    return ''.join(final_str)

试试这个:

text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'
splittext = text.split(".")
for x in range(5, len(splittext), 5):
    splittext[x] = "\n"+splittext[x].lstrip()
text = ".".join(splittext)
print(text)

使用正则表达式。在“[not.]后跟“.”的5个匹配项之后添加\n

import re
text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'

print(re.sub(r'((?:[^.]+\.\s*){5})',r'\1\n',text))

更高级的正则表达式句子匹配器,通过匹配结尾标点来处理缩写和其他标点。
参考资料:https://mikedombrowski.com/2017/04/regex-sentence-splitter/
注意:仍有一些边缘情况无法使用此选项,例如T.V.后面跟着Mr.需要双空格来表示单独的句子。带有句子的引文将被拆分。等等

import re
sentence_regex = r'((.*?([\.\?!][\'\"\u2018\u2019\u201c\u201d\)\]]*\s*(?<!\w\.\w.)(?<![A-Z][a-z][a-z]\.)(?<![A-Z][a-z]\.)(?<![A-Z]\.)\s+)){5})'
text = 'The puppy is cute. Watch T.V.  Mr. Summers is great. Say "my name."  My name is.  Or not... Happy friday? Sentence4. Sentence5. Sentence6. Sentence7.'
text += " " + text

print(re.sub(sentence_regex,r'\1\n',text))

任何比这更复杂的东西,您都可能需要查看语言处理工具包

相关问题 更多 >