仅拆分字符串中的长单词
我有一些随机的字符串,比如说:
s = "This string has some verylongwordsneededtosplit"
我想写一个函数叫做 trunc_string(string, len),这个函数的作用是接收一个字符串作为参数,'len' 是指在长单词后面要分割的字符数。
结果应该像这样:
str = trunc_string(s, 10)
str = "This string has some verylongwo rdsneededt osplit"
目前我有这样的代码:
def truncate_long_words(s, num):
"""Splits long words in string"""
words = s.split()
for word in words:
if len(word) > num:
split_words = list(words)
在这部分之后,我有一个长单词,它被分成了一个字符列表。现在我需要:
- 把 'num' 个字符放在一个临时的 word_part 列表中
- 把所有的 word_parts 合并成一个单词
- 把这个单词和其他没有被分割的单词连接起来。
我应该以某种类似的方式来做吗?:
counter = 0
for char in split_words:
word_part.append(char)
counter = counter+1
if counter == num
在这里,我应该把所有的 word_part 合并在一起,形成一个单词,然后继续进行下去。
4 个回答
5
一个选择是使用textwrap模块
http://docs.python.org/2/library/textwrap.html
下面是一个使用的例子:
>>> import textwrap
>>> s = "This string has some verylongwordsneededtosplit"
>>> list = textwrap.wrap(s, width=10)
>>> for line in list: print line;
...
This
string has
some veryl
ongwordsne
ededtospli
t
>>>
6
def split_word(word, length=10):
return (word[n:n+length] for n in range(0, len(word), length))
string = "This string has some verylongwordsneededtosplit"
print [item for word in string.split() for item in split_word(word)]
# ['This', 'string', 'has', 'some', 'verylongwo', 'rdsneededt', 'osplit']
注意:把你的字符串命名为 str
是个坏主意。这样会遮盖掉内置的类型。
3
为什么不这样做:
def truncate_long_words(s, num):
"""Splits long words in string"""
words = s.split()
for word in words:
if len(word) > num:
for i in xrange(0,len(word),num):
yield word[i:i+num]
else:
yield word
for t in truncate_long_words(s):
print t