我如何在python中将很长的字符串拆分为较短的字符串列表

|| 在我当前的django项目中,我有一个模型,该模型存储非常长的字符串(每个DB条目可以为5000-10000甚至更多个字符),然后我需要在用户调用记录时将它们拆分(实际上需要放在一个字符串中)记录在数据库中)。我需要的是返回一个较短字符串(列表中每个字符串100-500个字符)的列表(queryset?取决于是否在\“ SQL \”部分中,还是按原样获取所有列表并在视图中进行解析)。我返回到模板)。 我在任何地方都找不到python split命令,示例或任何答案。 我总是可以数词并追加,但可以数词....但是我敢肯定这种事情必须有某种功能.... 编辑:谢谢大家,但我想我听不懂,   例:      字符串:\“这是一个很长的字符串,包含很多很多很多其他句子,没有一个字符可以用来分割,只是按单词数\” 该字符串是Django模型的textField。 我需要将其拆分,每隔5个字说一次,这样我会得到: [\'这是一个很长的字符串\',\'有很多很多很多\',\'还有更多的句子,并且\',\'我没有一个字符可以使用,\' ',\',仅由单词的数字\',\'\']   事实是,几乎每种编程语言都按单词数划分实用程序功能,但我在python中找不到一种。 谢谢, 埃雷兹     
已邀请:
        
>>> s = \"This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words\"
>>> l = s.split()
>>> n = 5
>>> [\' \'.join(l[x:x+n]) for x in xrange(0, len(l), n)]
[\'This is a very long\',
 \'string with many many many\',
 \'many and many more sentences\',
 \'and there is not one\',
 \'character that i can use\',
 \'to split by, just by\',
 \'number of words\']
    
        这是一个主意:
def split_chunks(s, chunksize):
    pos = 0
    while(pos != -1):
        new_pos = s.rfind(\" \", pos, pos+chunksize)
        if(new_pos == pos):
            new_pos += chunksize # force split in word
        yield s[pos:new_pos]
        pos = new_pos
这将尝试将字符串拆分为最大长度为2的块。它尝试在空格处分割,但如果不能,则在单词中间分割:
>>> foo = \"asdf qwerty sderf sdefw regf\"
>>> list(split_chunks(foo, 6)
[\'asdf\', \' qwert\', \'y\', \' sderf\', \' sdefw\', \' regf\', \'\']
我想这需要一些调整(例如,如何处理单词中出现的拆分),但这应该为您提供一个起点。 要按字数划分,请执行以下操作:
def split_n_chunks(s, words_per_chunk):
    s_list = s.split()
    pos = 0
    while pos < len(s_list):
        yield s_list[pos:pos+words_per_chunk]
        pos += words_per_chunk
    

要回复问题请先登录注册