2010-10-05 118 views
0

如何将一个字符串拆分为python中多个单词的几个部分。例如,将一个10,000字的字符串转换为十个1,000字的字符串。谢谢。用python分割字符串的个数

+1

@ user201140:举一个例子 – pyfunc 2010-10-05 07:40:18

回答

4

这可能工作

def splitter(n, s): 
    pieces = s.split() 
    return (" ".join(pieces[i:i+n]) for i in xrange(0, len(pieces), n) 

for piece in splitter(1000, really_long_string): 
    print piece 

这将产生从10000字串10名1000字串就像你问。请注意,您也可以使用iterools石斑鱼配方,但这需要为您的字符串制作1000个迭代器副本:昂贵的我认为。

另请注意,这将取代所有空白的空格。如果这是不可接受的,你需要别的东西。

+1

缺少正确的parens? – 2010-10-05 07:59:12

+0

一如既往的好眼睛。 – aaronasterling 2010-10-05 08:00:46

2

正常情况下:

>>> a = "dedff fefef fefwff efef" 
>>> a.split() 
['dedff', 'fefef', 'fefwff', 'efef'] 
>>> k = a.split() 
>>> [" ".join(k[0:2]), " ".join(k[2:4])] 
['dedff fefef', 'fefwff efef'] 
>>> 
+0

不,按每个单词划分,而不是按选定数量的单词划分 – usertest 2010-10-05 07:42:54

+0

@ user201140:我想,我还没有理解这个问题。如果你能说明的话,这将是有用的。 – pyfunc 2010-10-05 07:45:36

+0

主要观点是使用分割。以下算法是蛋糕。我正在为pyfunc投票。 – 2010-10-05 07:47:14

0

Pehaps这样的事情,

>>> s = "aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt uu vv" 
>>> chunks = s.split() 
>>> per_line = 5 
>>> for i in range(0, len(chunks), per_line): 
...  print " ".join(chunks[i:i + per_line]) 
... 
aa bb cc dd ee 
ff gg hh ii jj 
kk ll mm nn oo 
pp qq rr ss tt 
uu vv 
0

这可能帮助:

s="blah blah .................." 
l =[] 
for i in xrange(0,len(s),1000): 
    l.append(s[i:i+1000]) 
1

试试这个:

s = 'a b c d e f g h i j k l' 
n = 3 

def group_words(s, n): 
    words = s.split() 
    for i in xrange(0, len(words), n): 
     yield ' '.join(words[i:i+n]) 

list(group_words(s,n)) 
['a b c', 'd e f', 'g h i', 'j k l'] 
+0

请注意,这相当于Aaron的生成器表达式。我觉得这个更具可读性。 – 2010-10-05 08:30:53

0

如果使用正则表达式很舒服,你也可以尝试这个:

import re 

def split_by_number_of_words(input, number_of_words): 
    regexp = re.compile(r'((?:\w+\W+){0,%d}\w+)' % (number_of_words - 1)) 
    return regexp.findall(input) 

s = ' '.join(str(n) for n in range(1, 101)) # "1 2 3 ... 100" 
for words in split_by_number_of_words(s, 10): 
    print words