如何在Python中将一个非常长的字符串拆分成多个较短的字符串列表

3
在我的django项目中,我有一个模型用于存储非常长的字符串(每个数据库条目可以达到5000-10000甚至更多个字符),然后当用户调用该记录时,我需要将其拆分(它确实需要在DB中的一个记录中)。我需要的是返回一个列表(查询集?取决于是在“SQL”部分还是按原样获取整个列表并在视图中进行解析)短字符串列表(列表中每个字符串的长度为100-500个字符),然后返回给模板。
我无法找到任何Python split命令或示例或任何答案... ...但我确定肯定有这种类型的函数存在....
编辑:谢谢大家,但我想我没被理解,
例如:字符串:“这是一个非常长的字符串,有许多句子,没有一个字符可以用来分割,只能按单词数分割”。
该字符串是django模型的textField。
我需要将其拆分,比如每5个单词,那么我会得到:
['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']
事实上,在几乎所有编程语言中,都有一种“按单词数拆分”的实用程序函数,但我找不到Python中的这种函数。
谢谢,Erez

你可能需要添加一个例子,以使问题更清晰。 - Björn Pollex
我更新了我的答案,以涵盖按单词数量拆分的方法。 - Björn Pollex
你看过 Django 工具中的 wrap 吗?模板过滤器中有类似的功能 - https://code.djangoproject.com/browser/django/trunk/django/utils/text.py#L11 - JamesO
2个回答

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

10倍'这太棒了,而且对于我的非常长的文本也不错 :-) - Erez

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接