如何在python中将很长的字符串拆分为较短的字符串列表 [英] How do i split a very long string into a list of shorter strings in python
问题描述
在我当前的django项目中,我有一个模型,该模型存储非常长的字符串(每个DB条目可以为5000-10000甚至更多个字符),然后我需要在用户调用记录时拆分它们(它确实需要在数据库中的一条记录中)。我需要的是返回一个较短字符串(我返回的列表中每个字符串100-500个字符)的列表(queryset?取决于是否在 SQL部分或按原样获取所有列表并在视图中进行解析)。
In my current django project I have a model that stores very long strings (can be 5000-10000 or even more characters per DB entry) and then i need to split them when a user is calling the record (it really need to be in one record in the DB). What i need is it to return a list (queryset? depends if in the "SQL" part or getting all the list as is and doing the parsing in the view) of shorter strings (100 - 500 characters per sting in the list i return to the template).
我找不到任何地方的python split命令,示例或任何答案……。
I couldn't find anywhere a python split command nor example or any kind of answer for that....
我总是可以算单词和追加单词,但是算单词....但是我敢肯定,某种东西必须要有某种功能....
I could always count words and append but count words.... but i am sure there has to be some kind of function for that sort of things....
编辑:谢谢大家,但我想我听不懂,
thank you everyone, but i guess i wasn't understood,
示例:
Example:
字符串:这是一个很长的字符串,包含许多很多很多其他句子,没有一个字符可以用来分割,只是按单词数
The String: "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"
字符串是Django模型的textField。
the string is a textField of django model.
我需要拆分它,说出每个 5个字,这样我就会得到:
i need to split it, lets say every 5 words so i will get:
[[这是一个很长的字符串,'有很多很多很多','还有很多句子,还有','没有一个字符','我可以使用到','由数字分隔','''''
问题是几乎每一个编程语言中,每词个数是一种工具功能,但我在python中找不到。
The thing is that is almost every programming languages there is split per number of words" kind of utility function but i can't find one in python.
谢谢,
Erez
thanks, Erez
推荐答案
>>> 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']
这篇关于如何在python中将很长的字符串拆分为较短的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!