簡體   English   中英

如何在一定數量的非空格字符后添加換行符?

[英]How can I add a newline after an amount of nonspace characters?

我正在嘗試在一定數量的字符后添加換行符並使其正常工作。

outfile.write('\n'.join(line[i:i+K] for i in range(0,len(line), K)))

我想修改它,以便不計算空格(非空格數量后的換行符)。

我已經對該主題進行了一些研究,但還沒有找到一個優雅的解決方案。 這個問題有一些表親,解決方案涉及textwrap幾個答案,但沒有什么能解決你的核心問題......

...這就是你想計算一個去內臟的字符串中的字符數,但將換行符應用到原始字符串中。 對此的解決方案將是一個有點折磨的鏈來維護這兩個索引。 你需要計算字母和空格; letter達到K的倍數時,您將生成的從上一個終點到 line[letter_count+space_count] 沿線向上饋送。

坦率地說,我認為為未來的編碼人員編寫、調試、維護和(尤其是)文檔是不值得的。 只需編寫循環以遍歷您的行。 這是痛苦的長版本:

line = "Now is the time for all good parties to come to the aid of man." + \
       "  It was the best of times, it was the worst of times."
K = 20

slugs = []
left = 0
count = 0
for idx, char in enumerate(line):
    if char != ' ':
        count += 1
    if count == K:
        count = 0
        slugs.append(line[left: idx+1])
        left = idx+1

slugs.append(line[left:])
print ('\n'.join(slugs))

輸出:

Now is the time for all go
od parties to come to the
 aid of man.  It was the bes
t of times, it was the wor
st of times.

像@Prune 一樣,我還沒有找到一種優雅的方法來優雅地使用任何現有的內置模塊來完成它——所以這是一種(另一種)手動完成的方法。

它的工作原理是從給定的可迭代對象創建一個由 K 個非空格字符組成的組列表,並在處理完其中的所有字符后返回該列表。

def grouper(iterable, K):
    nonspaced = []
    group = []
    count = 0
    for ch in iterable:
        group.append(ch)
        if ch != ' ':
            count += 1
            if count == 4:
                nonspaced.append(''.join(group))
                group = []
                count = 0
    if group:
        nonspaced.append(''.join(group))

    return nonspaced


K = 4
line = "I am trying to add a newline after a certain amount of characters."
for group in grouper(line, K):
    print(repr(group))

輸出:

I am t'
'ryin'
'g to a'
'dd a n'
'ewli'
'ne af'
'ter a'
' cert'
'ain a'
'moun'
't of c'
'hara'
'cter'
's.'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM