首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本缩进挑战

文本缩进挑战
EN

Stack Overflow用户
提问于 2022-09-17 20:57:23
回答 3查看 68关注 0票数 -3

如何编写一个函数,在每个字符之后打印带有2行新行的文本:".“、"?”和":“

**我不允许使用任何模块

**每行印刷线的开头或结尾不应有空位。

这是主要的功能:

代码语言:javascript
复制
text_indentation = __import__('5-text_indentation').text_indentation

text_indentation("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \
Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \
Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \
Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \
rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \
stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \
cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \
beatiorem! Iam ruinas videres""")

我的预期结果是:

Lorem ipsum dolor坐好了,敬请光临。

莫多吗?

Utrum igitur tibi litteram视频还是totas页面?

非临时的:

伊吉图尔·恩鲁德·基迪姆。

Fortasse最优,sed:

再加半杯汽水?

Teneo,我不干了,最后一次。

等等..。

我写了这篇文章:

代码语言:javascript
复制
def text_indentation(text):
    for i in text:
        if i == "." or i == "?" or i == ":" or i == ",":
            print(i, end="\n")
            print()
        else:
            print(i, end="")

但它会打印每行开头有空格的文本。

EN

回答 3

Stack Overflow用户

发布于 2022-09-17 21:28:55

也许我错过了什么,但似乎几次替换就能完成任务。

代码语言:javascript
复制
def text_indentation(text):
    print(text.replace(". ", ".\n\n").replace("? ", "?\n\n").replace(": ", ":\n\n"))
票数 3
EN

Stack Overflow用户

发布于 2022-09-17 21:18:14

您可以在打印空格之前检查该字母:

代码语言:javascript
复制
test = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \
Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \
Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \
Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \
rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \
stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \
cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \
beatiorem! Iam ruinas videres"""

def text_indentation(text):
    special_chars = [".", ":", "?", "!"]
    for idx, i in enumerate(text):
        if i in special_chars:
            print(i, end="\n")
            print()
        elif i == " ":
            if text[idx-1] in special_chars:
                continue
            else:
                print(i, end="")
        else:
            print(i, end="")

text_indentation(test)

您的代码中也有一个小错误:您似乎不希望在逗号后面出现行中断,但是根据您的代码,您确实要插入一个。另一个选项是设置一个布尔标志,以跳过.?!:之后的下一个字母。

编辑:我提到的后一种方法如下所示:

代码语言:javascript
复制
def text_indentation(text):
    skip_next = False
    for idx, i in enumerate(text):
        if skip_next:
            skip_next = False
            continue
        if i in [".", ":", "?", "!"]:
            print(i, end="\n")
            print()
            skip_next = True
        else:
            print(i, end="")

解决方案2更有效。

编辑2:你可能想考虑"!“也是。

票数 1
EN

Stack Overflow用户

发布于 2022-09-17 21:08:39

我会写一个这样的函数,它所做的实际上是检查文本中的字符是否对应于.,?或者A:如果是这样的话,它会将文本截断到找到字符的索引处,然后用两个换行符( \n )将其连接起来,并添加其余的文本。您可以使用<String>#strip()方法删除前导或尾随空格,并进一步检查换行符中的空格。

代码语言:javascript
复制
def format_text(text):
    # Split the text with 2 new lines after each of these characters: ".", "?" and ":"

    for i in range(len(text)): # Loop through the text 
        if text[i] in ".?:":
            text = text[:i+1] + "\n\n" + text[i+1:] # Add 2 new lines after each of these characters: ".", "?" and ":"
    # Remove the extra new lines at the beginning and at the end of the text
    text = text.strip()
    # make sure there are no spaces at the beginning or at the end of each printed line
    text = text.replace(" \n", "\n") # Remove the spaces at the beginning of each printed line
    text = text.replace("\n ", "\n") # Remove the spaces at the end of each printed line
    return text
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73758470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档