-4

I am Python beginner. Following code does exactly what i want. But it looks a little dump coz of three for loop. Can somebody show me smarter/shorter way to achieve it? may be a single function or parallelizing for loops.

def getWordListAndCounts(text):
  words = []  
  for t in text:
      for tt in t:
        for ttt in (re.split("\s+", str(tt))):
            words.append(str(ttt))
  return Counter(words) 

text = [['I like Apple' , 'I also like Google']]
getWordListAndCounts(text)
4
  • 1
    You could do it with one fewer loop if text was ['I like Apple' , 'I also like Google'] instead of [['I like Apple' , 'I also like Google']]. Why are you using double brackets, anyway?
    – Kevin
    Oct 8, 2015 at 17:51
  • Actually the Text come from another method >> def get_texts(reviews, score): texts = [] texts.append([r[0].lower() for r in reviews if r[1] == str(score)]) ; return texts
    – Max
    Oct 8, 2015 at 17:53
  • 3
    You may get better results posting here: codereview.stackexchange.com
    – MackM
    Oct 8, 2015 at 17:55
  • I'm voting to close this question as off-topic because it belongs on codereview.stackexchange.com
    – vaultah
    Nov 3, 2015 at 7:21

3 Answers 3

1

Firstly remove redundat list (it will reduce level in list comprehension):

Since there is not any necessity to store temporary result in list, generators are more preferable and efficient way. Check this one-line approach:

text = ['I like Apple' , 'I also like Google']
print Counter(str(ttt) for t in text for ttt in (re.split("\s+", str(t))))
0
  1. Use meaningful variable names. t, tt and ttt can't help the code being readable.
    Why not use "for phrase in text" then "for word in phrase"?
  2. Why are you using double encoded strings? Unless it is already in this format when you are reading it, I would suggest you not to do this.
-1
import re
from collections import Counter

def getWordListAndCounts(text):
    return Counter(re.split('\s+', str([' '.join(x) for x in text][0])))

text = [['I like Apple' , 'I also like Google']]
print getWordListAndCounts(text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.