如何将一个非常长的字符串拆分为python中较短字符串的列表

时间:2011-05-31 11:15:24

标签: python django django-queryset python-2.6

在我目前的django项目中,我有一个存储非常长字符串的模型(每个数据库条目可以是5000-10000甚至更多字符)然后我需要在用户调用记录时拆分它们(它确实需要在DB中的一个记录中)。我需要的是返回一个列表(queryset?取决于是否在“SQL”部分或者按原样获取所有列表并在视图中进行解析)更短的字符串(列表中每个sting 100到500个字符我返回到模板)。

我无法在任何地方找到python split命令,也没有示例或任何类型的答案......

我可以随时计算单词并附加但计算单词......但我确信必须有某种功能才能完成......

编辑:谢谢大家,但我想我不理解,

  

示例:

     

字符串:“这是一个非常长的字符串,有很多很多很多句子,没有一个字符我可以用来分割,只需按字数”

字符串是django模型的textField。

我需要拆分它,让我们说每个 5个字所以我会得到:

['这是一个非常长的字符串','有许多很多','还有更多的句子和','没有一个字符','我可以用来','分裂通过,只是数字','的单词']

  

事情是,几乎每种编程语言都有按字数分割“实用函数的种类但我在python中找不到。

感谢, 埃雷兹

2 个答案:

答案 0 :(得分:8)

>>> 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']

答案 1 :(得分:1)

这是一个想法:

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

这会尝试将字符串分成最多chunksize个字符串。它试图在空格处分裂,但如果不能在空格中分裂:

>>> 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