我是Python初学者。以下代码完全符合我的要求。但它看起来有点转储三个for循环。有人能告诉我更聪明/更短的实现方法吗?可以是单个函数或并行化循环。
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)
答案 0 :(得分:1)
首先删除冗余列表(它会降低列表理解中的级别):
由于没有必要将临时结果存储在列表中,因此生成器是更优选和有效的方式。 检查这种单线方法:
text = ['I like Apple' , 'I also like Google']
print Counter(str(ttt) for t in text for ttt in (re.split("\s+", str(t))))
答案 1 :(得分:0)
答案 2 :(得分:-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)