say I have a list of string elements
wordlist = ["hi what's up home diddle mc doo", "Oh wise master kakarot", "hello have a da"]
and I want each element in my list to have a maximum of say 3 words or 20 characters. Is there a function to do this?
Both can be done using list comprehension:
1) Max 20 characters:
new_list = [item[:20] for item in wordlist]
>>> new_list
["hi what's up home di", 'Oh wise master kakar', 'hello have a da']
2) Max 3 words:
new_list = [' '.join(item.split()[:3]) for item in wordlist if item]
>>> new_list
["hi what's up", 'Oh wise master', 'hello have a']
Here's how you would do this using the builtin map function (with lambda expressions)
20 character limit
wordlist = ["hi what's up home diddle mc doo", "Oh wise master kakarot"]
new_wordlist = map(lambda x: x[:20], wordlist)
>>> ["hi what's up home di", 'Oh wise master kakar']
3 word limit
wordlist = ["hi what's up home diddle mc doo", "Oh wise master kakarot"]
new_wordlist = map(lambda x: ' '.join(x.split(' ')[:3]), wordlist)
>>> ["hi what's up", 'Oh wise master']
You can do it together with this code:
import sys
wordCount = int(sys.argv[1])
charCount = int(sys.argv[2])
wordlist = ["hi what's up home diddle mc doo", "Oh wise master kakarot", "hello have a da"]
print(wordlist)
for i in range(len(wordlist)):
currItem = wordlist[i]
splitItems = currItem.split(" ")
length = sum(len(s) for s in splitItems[0:wordCount])
index = wordCount
while(length > charCount):
index -= 1
length = sum(len(s) for s in splitItems[0:index])
pass
wordlist[i] = ' '.join(splitItems[0:index])
pass
print(wordlist)