用Python编写代码的较短方法
我是Python初学者。下面的代码正是我想要的。但它看起来有点像垃圾堆,因为它有三个循环。有人能告诉我更聪明/更短的方法来实现它吗?可以是单个函数,也可以是循环的并行化用Python编写代码的较短方法,python,Python,我是Python初学者。下面的代码正是我想要的。但它看起来有点像垃圾堆,因为它有三个循环。有人能告诉我更聪明/更短的方法来实现它吗?可以是单个函数,也可以是循环的并行化 def getWordListAndCounts(text): words = [] for t in text: for tt in t: for ttt in (re.split("\s+", str(tt))): words.append(str(ttt))
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)
首先删除冗余列表(这将降低列表理解的级别): 因为并没有必要将临时结果存储在列表中,所以生成器是更可取和有效的方法。 检查此单线方法:
text = ['I like Apple' , 'I also like Google']
print Counter(str(ttt) for t in text for ttt in (re.split("\s+", str(t))))
为什么不使用“文本中的短语”然后使用“短语中的单词”李>
如果
text
是[“我喜欢苹果”,“我也喜欢谷歌”]
而不是[[“我喜欢苹果”,“我也喜欢谷歌”]
,你就可以少做一个循环。无论如何,为什么要使用双括号?实际上,文本来自另一种方法>>def get_Text(评论,分数):Text=[]Text.append([r[0]。如果r[1]==str(分数)],则评论中r的下限();return text你可能会在这里得到更好的结果:我投票决定把这个问题作为离题题来结束,因为它属于主题
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)