gpt4 book ai didi

python - 如何分割字符串,使其包含少于 n 个字符并进行扭曲

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:13 25 4
gpt4 key购买 nike

我有一个很长的字符串,我想将其保存到文件中。单词之间用空格分隔。已知长字符串中的单词数可以被3整除。

基本上我正在寻找一种将字符串分割成 block 的方法。每个 block 小于 n 个字符, block 中的单词数也能被 3 整除。

例如

>>> longstring = "This is a very long string and the sum of words is divisible by three"
>>> len(longstring.split())
>>> 15

假设最大行长度为 n=30:

>>>split_string(longstring, 30)
['This is a very long string', 'and the sum of words is', 'divisible by three']

总而言之,规则是:

  1. 行的长度不能超过 n 个字符。
  2. 一个不同之处是每个新行必须包含 3 个单词的倍数。

到目前为止,我尝试使用textwrap,但我不知道如何实现2。

import textwrap    
textwrap.fill(long_line, width=69)

最佳答案

如果您确定字符串中的单词总数始终能被 3 整除,则可以执行以下操作:

import sys
#long string; 84 words; divisible by 3
longString = "The charges are still sealed under orders from a federal judge. Plans were prepared Friday for anyone charged to be into custody as soon as Monday, the sources said. It is unclear what the charges are. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning."
#convert string to list
listOfWords = longString.split()
#list to contain lines
lines = []
#make sure number of words is divisible by 3
if len(listOfWords) % 3 != 0:
#exit
print "words number is not divisible by 3"
sys.exit()
#keep going until list is empty
while listOfWords:

i = 0
line = ""
#loop for every line
while True:
#puts the next 3 words into a string
temp = " ".join(listOfWords[i:i+3])
#check new length of line after adding the new 3 words, if it is still less than 70, add the words, otherwise break out of the loop
if len(line) + len(temp) > 70:
break
line += "{} ".format(temp)
i+=3
#remove finished words from the list completely
listOfWords = listOfWords[i:]
#adds line into result list
lines.append(line.strip())

#to make sure this works
for line in lines:
print len(str(line))
print "Number of words: {}".format(len(line.split()))
print "number of chars: {}".format(len(line))
print line
print "----------------------------------------"

关于python - 如何分割字符串,使其包含少于 n 个字符并进行扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com